(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.BonreeAgent = {}));
})(this, (function (exports) { 'use strict';

  var version = "2.1.7";

  function supportsLabelProperty() {
      var supportsLabelPropertyResult = 'labels' in HTMLInputElement.prototype?true:false;
       return supportsLabelPropertyResult
   }
   function getTextualContent(element) {
       if (element.isContentEditable) {
         return
       }
     
       if ('innerText' in element) {
         let text = element.innerText;
         const removeTextFromElements = (query) => {
           const list = element.querySelectorAll(query);
           for (let index = 0; index < list.length; index += 1) {
             const element = list[index];
             if ('innerText' in element) {
               const textToReplace = element.innerText;
               if (textToReplace && textToReplace.trim().length > 0) {
                 text = text.replace(textToReplace, '');
               }
             }
           }
         };
     
         if (!supportsInnerTextScriptAndStyleRemoval()) {
           // remove the inner text of SCRIPT and STYLES from the result. This is a bit dirty, but should
           // be relatively fast and work in most cases.
           removeTextFromElements('script, style');
         }
         return text
       }
       return element.textContent
     }
   function find(arr,callback){
       for(var i=0;i<arr.length;i++){
           return callback(i)
       }
       return undefined
   }
   function safeTruncate(candidate,length,suffix = '') {
       const lastChar = candidate.charCodeAt(length - 1);
       const isLastCharSurrogatePair = lastChar >= 0xd800 && lastChar <= 0xdbff;
       const correctedLength = isLastCharSurrogatePair ? length + 1 : length;
       if (candidate.length <= correctedLength) {
         return candidate
       }
       return `${candidate.slice(0, correctedLength)}${suffix}`
     }
   function truncate(s) {
       return s.length > 100 ? `${safeTruncate(s, 100)} [...]` : s
     }
   function normalizeWhitespace(s) {
       return s.replace(/\s+/g, ' ')
   }
   function getElementById(Element, id) {
       return Element.ownerDocument ? Element.ownerDocument.getElementById(id) : null
   }
   const priorityStrategies= [
       // associated LABEL text
       (element) => {
           // IE does not support element.labels, so we fallback to a CSS selector based on the element id
           // instead
           if (supportsLabelProperty()) {
               if ('labels' in element && element.labels && element.labels.length > 0) {
                   return getTextualContent(element.labels[0])
               }
           } else if (element.id) {
               const label =
                   element.ownerDocument &&
                   find(element.ownerDocument.querySelectorAll('label'), (label) => label.htmlFor === element.id);
               return label && getTextualContent(label)
           }
       },
       // INPUT button (and associated) value
       (element) => {
           if (element.nodeName === 'INPUT') {
               const input = element;
               const type = input.getAttribute('type');
               if (type === 'button' || type === 'submit' || type === 'reset') {
                   return input.value
               }
           }
       },
       // BUTTON, LABEL or button-like element text
       (element) => {
           if (element.nodeName === 'BUTTON' || element.nodeName === 'LABEL' || element.getAttribute('role') === 'button') {
               return getTextualContent(element)
           }
       },
       (element) => element.getAttribute('aria-label'),
       // associated element text designated by the aria-labelledby attribute
       (element) => {
           const labelledByAttribute = element.getAttribute('aria-labelledby');
           if (labelledByAttribute) {
               return labelledByAttribute
                   .split(/\s+/)
                   .map((id) => getElementById(element, id))
                   .filter((label) => Boolean(label))
           .map((element) => getTextualContent(element))
                   .join(' ')
           }
       },
       (element) => element.getAttribute('alt'),
       (element) => element.getAttribute('name'),
       (element) => element.getAttribute('title'),
       (element) => element.getAttribute('placeholder'),
       // SELECT first OPTION text
       (element) => {
           if ('options' in element && element.options.length > 0) {
               return getTextualContent(element.options[0])
           }
       },
   ];
   function supportsInnerTextScriptAndStyleRemoval() {
       return !isIE()
     }
   function isIE() {
   return Boolean(document.documentMode)
   }
   
   const fallbackStrategies= [
       (element) => getTextualContent(element)
   ];
   const MAX_PARENTS_TO_CONSIDER = 10;
   function getActionNameFromElementForStrategies(
       targetElement,
       strategies
   ) {
       let element= targetElement;
       let recursionCounter = 0;
       while (
           recursionCounter <= MAX_PARENTS_TO_CONSIDER &&
           element &&
           element.nodeName !== 'BODY' &&
           element.nodeName !== 'HTML' &&
           element.nodeName !== 'HEAD'
           ) {
           for (const strategy of strategies) {
               const name = strategy(element);
               if (typeof name === 'string') {
                   const trimmedName = name.trim();
                   if (trimmedName) {
                       return truncate(normalizeWhitespace(trimmedName))
                     }
               }
           }
           // Consider a FORM as a contextual limit to get the action name.  This is experimental and may
           // be reconsidered in the future.
           if (element.nodeName === 'FORM') {
               break
           }
           element = element.parentElement;
           recursionCounter += 1;
       }
   }
   /** 
    * @descripe 跟据不同的策略获取target的有效文本信息
    * @param {*} target event.target
    * @return 有效文本信息
    **/
   function getActionText(target){
       return getActionNameFromElementForStrategies(target,priorityStrategies)||getActionNameFromElementForStrategies(target,fallbackStrategies)||''
   }

  /*
   * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
   * Digest Algorithm, as defined in RFC 1321.
   * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
   * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
   * Distributed under the BSD License
   * See http://pajhome.org.uk/crypt/md5 for more info.
   */

  // var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance   */
  var chrsz = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

  /*
   * These are the functions you'll usually want to call
   * They take string arguments and return either hex or base-64 encoded strings
   */
  function hex_md5(s) {
      return binl2hex(core_md5(str2binl(s), s.length * chrsz));
  }

  // export function b64_md5(s) {
  //     return binl2b64(core_md5(str2binl(s), s.length * chrsz));
  // }

  /*
   * Calculate the MD5 of an array of little-endian words, and a bit length
   */
  function core_md5(x, len) {
      /* append padding */
      x[len >> 5] |= 0x80 << ((len) % 32);
      x[(((len + 64) >>> 9) << 4) + 14] = len;

      var a = 1732584193;
      var b = -271733879;
      var c = -1732584194;
      var d = 271733878;

      for (var i = 0; i < x.length; i += 16) {
          var olda = a;
          var oldb = b;
          var oldc = c;
          var oldd = d;

          a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
          d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
          c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
          b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
          a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
          d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
          c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
          b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
          a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
          d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
          c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
          b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
          a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
          d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
          c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
          b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);

          a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
          d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
          c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
          b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
          a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
          d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
          c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
          b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
          a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
          d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
          c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
          b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
          a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
          d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
          c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
          b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);

          a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
          d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
          c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
          b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
          a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
          d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
          c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
          b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
          a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
          d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
          c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
          b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
          a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
          d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
          c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
          b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);

          a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
          d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
          c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
          b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
          a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
          d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
          c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
          b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
          a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
          d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
          c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
          b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
          a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
          d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
          c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
          b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);

          a = safe_add(a, olda);
          b = safe_add(b, oldb);
          c = safe_add(c, oldc);
          d = safe_add(d, oldd);
      }
      return Array(a, b, c, d);

  }

  /*
   * These functions implement the four basic operations the algorithm uses.
   */
  function md5_cmn(q, a, b, x, s, t) {
      return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
  }

  function md5_ff(a, b, c, d, x, s, t) {
      return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
  }

  function md5_gg(a, b, c, d, x, s, t) {
      return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
  }

  function md5_hh(a, b, c, d, x, s, t) {
      return md5_cmn(b ^ c ^ d, a, b, x, s, t);
  }

  function md5_ii(a, b, c, d, x, s, t) {
      return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
  }

  /*
   * Add integers, wrapping at 2^32. This uses 16-bit operations internally
   * to work around bugs in some JS interpreters.
   */
  function safe_add(x, y) {
      var lsw = (x & 0xFFFF) + (y & 0xFFFF);
      var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
      return (msw << 16) | (lsw & 0xFFFF);
  }

  /*
   * Bitwise rotate a 32-bit number to the left.
   */
  function bit_rol(num, cnt) {
      return (num << cnt) | (num >>> (32 - cnt));
  }

  /*
   * Convert a string to an array of little-endian words
   * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
   */
  function str2binl(str) {
      var bin = Array();
      var mask = (1 << chrsz) - 1;
      for (var i = 0; i < str.length * chrsz; i += chrsz)
          bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32);
      return bin;
  }

  /*
   * Convert an array of little-endian words to a hex string.
   */
  function binl2hex(binarray) {
      var hex_tab = "0123456789abcdef";
      var str = "";
      for (var i = 0; i < binarray.length * 4; i++) {
          str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) +
              hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF);
      }
      return str;
  }

  /*
   * Convert an array of little-endian words to a base-64 string
   */
  // function binl2b64(binarray) {
  //     var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  //     var str = "";
  //     for (var i = 0; i < binarray.length * 4; i += 3) {
  //         var triplet = (((binarray[i >> 2] >> 8 * (i % 4)) & 0xFF) << 16)
  //             | (((binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4)) & 0xFF) << 8)
  //             | ((binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4)) & 0xFF);
  //         for (var j = 0; j < 4; j++) {
  //             if (i * 8 + j * 6 > binarray.length * 32) str += b64pad;
  //             else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);
  //         }
  //     }
  //     return str;
  // }

  let typesArr = {
      "3dm": "x-world/x-3dmf",
      "3dmf": "x-world/x-3dmf",
      "a": "application/octet-stream",
      "aab": "application/x-authorware-bin",
      "aam": "application/x-authorware-map",
      "aas": "application/x-authorware-seg",
      "abc": "text/vndabc",
      "acgi": "text/html",
      "afl": "video/animaflex",
      "ai": "application/postscript",
      "aif": "audio/x-aiff",
      "aifc": "audio/x-aiff",
      "aiff": "audio/x-aiff",
      "aim": "application/x-aim",
      "aip": "text/x-audiosoft-intra",
      "ani": "application/x-navi-animation",
      "aos": "application/x-nokia-9000-communicator-add-on-software",
      "aps": "application/mime",
      "arc": "application/octet-stream",
      "arj": "application/octet-stream",
      "art": "image/x-jg",
      "asf": "video/x-ms-asf",
      "asm": "text/x-asm",
      "asp": "text/asp",
      "asx": "application/x-mplayer2",
      "au": "audio/x-au",
      "avi": "video/avi",
      "bcpio": "application/x-bcpio",
      "bin": "application/x-macbinary",
      "bm": "image/bmp",
      "bmp": "image/x-windows-bmp",
      "boo": "application/book",
      "book": "application/book",
      "boz": "application/x-bzip2",
      "bsh": "application/x-bsh",
      "bz": "application/x-bzip",
      "bz2": "application/x-bzip2",
      "c": "text/plain",
      "c++": "text/plain",
      "cat": "application/vndms-pki.seccat",
      "cc": "text/plain",
      "ccad": "application/clariscad",
      "cco": "application/x-cocoa",
      "cdf": "application/x-cdf",
      "cer": "application/pkix-cert",
      "cha": "application/x-chat",
      "chat": "application/x-chat",
      "class": "application/x-java-class",
      "com": "application/octet-stream",
      "conf": "text/plain",
      "cpio": "application/x-cpio",
      "cpp": "text/x-c",
      "cpt": "application/x-cpt",
      "crl": "application/pkcs-crl",
      "crt": "application/x-x509-ca-cert",
      "csh": "application/x-csh",
      "css": "application/x-pointplus",
      "cxx": "text/plain",
      "dcr": "application/x-director",
      "deepv": "application/x-deepv",
      "der": "application/x-x509-ca-cert",
      "dif": "video/x-dv",
      "dir": "application/x-director",
      "dl": "video/dl",
      "doc": "application/msword",
      "dot": "application/msword",
      "dp": "application/commonground",
      "drw": "application/drafting",
      "dump": "application/octet-stream",
      "dv": "video/x-dv",
      "dvi": "application/x-dvi",
      "dwf": "model/vnd.dwf",
      "dwg": "application/acad",
      "dxf": "application/dxf",
      "dxr": "application/x-director",
      "el": "text/x-script.elisp",
      "elc": "application/x-bytecode.elisp compiled elisp)",
      "env": "application/x-envoy",
      "eps": "application/postscript",
      "es": "application/x-esrehber",
      "etx": "text/x-setext",
      "evy": "application/x-envoy",
      "exe": "application/octet-stream",
      "f": "text/x-fortran",
      "f77": "text/x-fortran",
      "f90": "text/x-fortran",
      "fdf": "application/vnd.fdf",
      "fif": "application/fractals",
      "fli": "video/x-fli",
      "flo": "image/florian",
      "flx": "text/vnd.fmi.flexstor",
      "fmf": "video/x-atomic3d-feature",
      "for": "text/x-fortran",
      "fpx": "image/vnd.net-fpx",
      "frl": "application/freeloader",
      "funk": "audio/make",
      "g": "text/plain",
      "g3": "image/g3fax",
      "gif": "image/gif",
      "gl": "video/x-gl",
      "gsd": "audio/x-gsm",
      "gsm": "audio/x-gsm",
      "gsp": "application/x-gsp",
      "gss": "application/x-gss",
      "gtar": "application/x-gtar",
      "gz": "application/x-compressed",
      "gzip": "application/x-gzip",
      "h": "text/x-h",
      "hdf": "application/x-hdf",
      "help": "application/x-helpfile",
      "hgl": "application/vnd.hp-hpgl",
      "hh": "text/x-h",
      "hlb": "text/x-script",
      "hlp": "application/x-winhelp",
      "hpg": "application/vnd.hp-hpgl",
      "hpgl": "application/vnd.hp-hpgl",
      "hqx": "application/binhex",
      "hta": "application/hta",
      "htc": "text/x-component",
      "htm": "text/html",
      "html": "text/html",
      "htmls": "text/html",
      "htt": "text/webviewhtml",
      "htx": "text/html",
      "ice": "x-conference/x-cooltalk",
      "ico": "image/x-icon",
      "idc": "text/plain",
      "ief": "image/ief",
      "iefs": "image/ief",
      "iges": "application/iges",
      "igs": "model/iges",
      "ima": "application/x-ima",
      "imap": "application/x-httpd-imap",
      "inf": "application/inf",
      "ins": "application/x-internett-signup",
      "ip": "application/x-ip2",
      "isu": "video/x-isvideo",
      "it": "audio/it",
      "iv": "application/x-inventor",
      "ivr": "i-world/i-vrml",
      "ivy": "application/x-livescreen",
      "jam": "audio/x-jam",
      "jav": "text/x-java-source",
      "java": "text/x-java-source",
      "jcm": "application/x-java-commerce",
      "jfif": "image/pjpeg",
      "jfif-tbnl": "image/jpeg",
      "jpe": "image/pjpeg",
      "jpeg": "image/pjpeg",
      "jpg": "image/pjpeg",
      "jps": "image/x-jps",
      "js": "application/x-javascript",
      "jut": "image/jutvision",
      "kar": "audio/midi",
      "ksh": "application/x-ksh",
      "la": "audio/x-nspaudio",
      "lam": "audio/x-liveaudio",
      "latex": "application/x-latex",
      "lha": "application/octet-stream",
      "lhx": "application/octet-stream",
      "list": "text/plain",
      "lma": "audio/x-nspaudio",
      "log": "text/plain",
      "lsp": "application/x-lisp",
      "lst": "text/plain",
      "lsx": "text/x-la-asf",
      "ltx": "application/x-latex",
      "lzh": "application/octet-stream",
      "lzx": "application/octet-stream",
      "m": "text/x-m",
      "m1v": "video/mpeg",
      "m2a": "audio/mpeg",
      "m2v": "video/mpeg",
      "m3u": "audio/x-mpequrl",
      "man": "application/x-troff-man",
      "map": "application/x-navimap",
      "mar": "text/plain",
      "mbd": "application/mbedlet",
      "mc$": "application/x-magic-cap-package-1.0",
      "mcd": "application/x-mathcad",
      "mcf": "text/mcf",
      "mcp": "application/netmc",
      "me": "application/x-troff-me",
      "mht": "message/rfc822",
      "mhtml": "message/rfc822",
      "mid": "application/x-midi",
      "midi": "application/x-midi",
      "mif": "application/x-mif",
      "mime": "www/mime",
      "mjf": "audio/x-vnd.audioexplosion.mjuicemediafile",
      "mjpg": "video/x-motion-jpeg",
      "mm": "application/x-meme",
      "mod": "audio/x-mod",
      "moov": "video/quicktime",
      "mov": "video/quicktime",
      "movie": "video/x-sgi-movie",
      "mp2": "audio/x-mpeg",
      "mp3": "audio/x-mpeg-3",
      "mpa": "audio/mpeg",
      "mpc": "application/x-project",
      "mpe": "video/mpeg",
      "mpeg": "video/mpeg",
      "mpg": "video/mpeg",
      "mpga": "audio/mpeg",
      "mpp": "application/vnd.ms-project",
      "mpt": "application/x-project",
      "mpv": "application/x-project",
      "mpx": "application/x-project",
      "mrc": "application/marc",
      "ms": "application/x-troff-ms",
      "mv": "video/x-sgi-movie",
      "my": "audio/make",
      "mzz": "application/x-vnd.audioexplosion.mzz",
      "nap": "image/naplps",
      "naplps": "image/naplps",
      "nc": "application/x-netcdf",
      "ncm": "application/vnd.nokia.configuration-message",
      "nif": "image/x-niff",
      "niff": "image/x-niff",
      "nix": "application/x-mix-transfer",
      "nsc": "application/x-conference",
      "nvd": "application/x-navidoc",
      "o": "application/octet-stream",
      "oda": "application/oda",
      "omc": "application/x-omc",
      "omcd": "application/x-omcdatamaker",
      "omcr": "application/x-omcregerator",
      "p": "text/x-pascal",
      "p10": "application/x-pkcs10",
      "p12": "application/x-pkcs12",
      "p7a": "application/x-pkcs7-signature",
      "p7c": "application/x-pkcs7-mime",
      "p7m": "application/x-pkcs7-mime",
      "p7r": "application/x-pkcs7-certreqresp",
      "p7s": "application/pkcs7-signature",
      "part": "application/pro_eng",
      "pas": "text/pascal",
      "pbm": "image/x-portable-bitmap",
      "pcl": "application/x-pcl",
      "pcx": "image/x-pcx",
      "pdb": "chemical/x-pdb",
      "pdf": "application/pdf",
      "pfunk": "audio/make.my.funk",
      "pgm": "image/x-portable-greymap",
      "pic": "image/pict",
      "pict": "image/pict",
      "pkg": "application/x-newton-compatible-pkg",
      "pko": "application/vnd.ms-pki.pko",
      "pl": "text/x-script.perl",
      "plx": "application/x-pixclscript",
      "pm": "text/x-script.perl-module",
      "pm4": "application/x-pagemaker",
      "pm5": "application/x-pagemaker",
      "png": "image/png",
      "pnm": "application/x-portable-anymap",
      "pot": "application/mspowerpoint",
      "pov": "model/x-pov",
      "ppa": "application/vnd.ms-powerpoint",
      "ppm": "image/x-portable-pixmap",
      "pps": "application/vnd.ms-powerpoint",
      "ppt": "application/powerpoint",
      "ppz": "application/mspowerpoint",
      "pre": "application/x-freelance",
      "prt": "application/pro_eng",
      "ps": "application/postscript",
      "psd": "application/octet-stream",
      "pvu": "paleovu/x-pv",
      "pwz": "application/vnd.ms-powerpoint",
      "py": "text/x-script.phyton",
      "pyc": "application/x-bytecode.python",
      "qcp": "audio/vnd.qcelp",
      "qd3": "x-world/x-3dmf",
      "qd3d": "x-world/x-3dmf",
      "qif": "image/x-quicktime",
      "qt": "video/quicktime",
      "qtc": "video/x-qtc",
      "qti": "image/x-quicktime",
      "qtif": "image/x-quicktime",
      "ra": "audio/x-realaudio",
      "ram": "audio/x-pn-realaudio",
      "ras": "application/x-cmu-raster",
      "rast": "image/cmu-raster",
      "rexx": "text/x-script.rexx",
      "rf": "image/vnd.rn-realflash",
      "rgb": "image/x-rgb",
      "rm": "application/vnd.rn-realmedia",
      "rmm": "audio/x-pn-realaudio",
      "rmp": "audio/x-pn-realaudio-plugin",
      "rng": "application/vnd.nokia.ringing-tone",
      "rnx": "application/vnd.rn-realplayer",
      "roff": "application/x-troff",
      "rp": "image/vnd.rn-realpix",
      "rpm": "audio/x-pn-realaudio-plugin",
      "rt": "text/vnd.rn-realtext",
      "rtf": "application/x-rtf",
      "rtx": "application/rtf",
      "rv": "video/vnd.rn-realvideo",
      "s": "text/x-asm",
      "s3m": "audio/s3m",
      "saveme": "application/octet-stream",
      "sbk": "application/x-tbook",
      "scm": "application/x-lotusscreencam",
      "sdml": "text/plain",
      "sdp": "application/x-sdp",
      "sdr": "application/sounder",
      "sea": "application/x-sea",
      "set": "application/set",
      "sgm": "text/x-sgml",
      "sgml": "text/x-sgml",
      "sh": "application/x-sh",
      "shar": "application/x-shar",
      "shtml": "text/x-server-parsed-html",
      "sid": "audio/x-psid",
      "sit": "application/x-sit",
      "skd": "application/x-koan",
      "skm": "application/x-koan",
      "skp": "application/x-koan",
      "skt": "application/x-koan",
      "sl": "application/x-seelogo",
      "smi": "application/smil",
      "smil": "application/smil",
      "snd": "audio/x-adpcm",
      "sol": "application/solids",
      "spc": "application/x-pkcs7-certificates",
      "spl": "application/futuresplash",
      "spr": "application/x-sprite",
      "sprite": "application/x-sprite",
      "src": "application/x-wais-source",
      "ssi": "text/x-server-parsed-html",
      "ssm": "application/streamingmedia",
      "sst": "application/vnd.ms-pki.certstore",
      "step": "application/step",
      "stl": "application/vnd.ms-pki.stl",
      "stp": "application/step",
      "sv4cpio": "application/x-sv4cpio",
      "sv4crc": "application/x-sv4crc",
      "svf": "image/x-dwg",
      "svr": "application/x-world",
      "swf": "application/x-shockwave-flash",
      "t": "application/x-troff",
      "talk": "text/x-speech",
      "tar": "application/x-tar",
      "tbk": "application/toolbook",
      "tcl": "application/x-tcl",
      "tcsh": "text/x-script.tcsh",
      "tex": "application/x-tex",
      "texi": "application/x-texinfo",
      "texinfo": "application/x-texinfo",
      "text": "application/plain",
      "tgz": "application/gnutar",
      "tif": "image/x-tiff",
      "tiff": "image/x-tiff",
      "tr": "application/x-troff",
      "tsi": "audio/tsp-audio",
      "tsp": "application/dsptype",
      "tsv": "text/tab-separated-values",
      "turbot": "image/florian",
      "txt": "text/plain",
      "uil": "text/x-uil",
      "uni": "text/uri-list",
      "unis": "text/uri-list",
      "unv": "application/i-deas",
      "uri": "text/uri-list",
      "uris": "text/uri-list",
      "ustar": "application/x-ustar",
      "uu": "application/octet-stream",
      "uue": "text/x-uuencode",
      "vcd": "application/x-cdlink",
      "vcs": "text/x-vcalendar",
      "vda": "application/vda",
      "vdo": "video/vdo",
      "vew": "application/groupwise",
      "viv": "video/vivo",
      "vivo": "video/vivo",
      "vmd": "application/vocaltec-media-desc",
      "vmf": "application/vocaltec-media-file",
      "voc": "audio/x-voc",
      "vos": "video/vosaic",
      "vox": "audio/voxware",
      "vqe": "audio/x-twinvq-plugin",
      "vqf": "audio/x-twinvq",
      "vql": "audio/x-twinvq-plugin",
      "vrml": "application/x-vrml",
      "vrt": "x-world/x-vrt",
      "vsd": "application/x-visio",
      "vst": "application/x-visio",
      "vsw": "application/x-visio",
      "w60": "application/wordperfect6.0",
      "w61": "application/wordperfect6.1",
      "w6w": "application/msword",
      "wav": "audio/x-wav",
      "wb1": "application/x-qpro",
      "wbmp": "image/vnd.wap.wbmp",
      "web": "application/vnd.xara",
      "wiz": "application/msword",
      "wk1": "application/x-123",
      "wmf": "windows/metafile",
      "wml": "text/vnd.wap.wml",
      "wmlc": "application/vnd.wap.wmlc",
      "wmls": "text/vnd.wap.wmlscript",
      "wmlsc": "application/vnd.wap.wmlscriptc",
      "word": "application/msword",
      "wp": "application/wordperfect",
      "wp5": "application/wordperfect",
      "wp6": "application/wordperfect",
      "wpd": "application/wordperfect",
      "wq1": "application/x-lotus",
      "wri": "application/x-wri",
      "wrl": "application/x-world",
      "wrz": "model/vrml",
      "wsc": "text/scriplet",
      "wsrc": "application/x-wais-source",
      "wtk": "application/x-wintalk",
      "xbm": "image/x-xbitmap",
      "xdr": "video/x-amt-demorun",
      "xgz": "xgl/drawing",
      "xif": "image/vnd.xiff",
      "xl": "application/excel",
      "xla": "application/x-msexcel",
      "xlb": "application/x-excel",
      "xlc": "application/x-excel",
      "xld": "application/x-excel",
      "xlk": "application/x-excel",
      "xll": "application/x-excel",
      "xlm": "application/x-excel",
      "xls": "application/excel",
      "xlt": "application/excel",
      "xlv": "application/x-excel",
      "xlw": "application/vnd.ms-excel",
      "xm": "audio/xm",
      "xml": "application/xml",
      "xmz": "xgl/movie",
      "xpix": "application/x-vnd.ls-xpix",
      "xpm": "image/x-xpixmap",
      "x-png": "image/png",
      "xsr": "video/x-amt-showrun",
      "xwd": "image/x-xwindowdump",
      "xyz": "chemical/x-pdb",
      "z": "application/x-compressed",
      "zip": "multipart/x-zip",
      "zoo": "application/octet-stream",
      "zsh": "text/x-script.zsh"
    };
  function getMineTypeByHeader(header, defaultMineType="text/html") {
      if (isEmpty(header)) {
        return defaultMineType
      }
      let contentType = header['Content-Type'] || header['content-type'] || defaultMineType;
      let contentTypes = contentType.split(';');
      return contentTypes[0].trim();
    }
  function getMineTypeByUrl(url){
      let def = "text/html";
      if (isEmpty(url)) {
        return def;
      }
      return getMineTypeBySuffixes(getTakeSuffixes(url),def)
    }
    function getTakeSuffixes(url) {
      if (isEmpty(url)) {
        return ''
      }
      let  takeSuffixes = "";
      let  lastIndexRadix = url.lastIndexOf(".");
      if (lastIndexRadix != -1) {
          let endIndex = url.indexOf("?", lastIndexRadix);
          if (endIndex == -1) {
              endIndex = url.length;
          }
          takeSuffixes = url.substring(lastIndexRadix+1, endIndex);
      }
      return takeSuffixes
    }
    function getMineTypeBySuffixes(suffixes,defaultMineType) {
      if (isEmpty(suffixes)) {
        return defaultMineType
      }
      let takeSuffixeMapResult=typesArr[suffixes];
      return isEmpty(takeSuffixeMapResult) ? defaultMineType : takeSuffixeMapResult;
    }

  function getRandom (t) {
      return t < 0
        ? NaN : t <= 30
          ? 0 | Math.random() * (1 << t) : t <= 53
            ? (0 | Math.random() * (1 << 30)) + (0 | Math.random() * (1 << t - 30)) * (1 << 30) : NaN
    }
    
    function toHex (t, e) {
      for (var r = t.toString(16), n = e - r.length, a = '0'; n > 0; n >>>= 1, a += a) {
        1 & n && (r = a + r);
      }
      return r
    }
    
    function uuid() {
      return toHex(getRandom(32), 8) + '-' +
        toHex(getRandom(16), 4) + '-' +
        toHex(16384 | getRandom(12), 4) + '-' +
        toHex(32768 | getRandom(14), 4) + '-' +
        toHex(getRandom(48), 12)
    }
    
    function uuidWithLength(l){
      if(l==16){
        return toHex(getRandom(32), 8)+toHex(getRandom(32), 8)
      }
      if(l==32){
        return toHex(getRandom(32), 8)+toHex(getRandom(32), 8)+toHex(getRandom(32), 8)+toHex(getRandom(32), 8)
      }
    }
    
    function skyUuid(){
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        /* tslint:disable */
        const r = (Math.random() * 16) | 0;
        /* tslint:disable */
        const v = c === 'x' ? r : (r & 0x3) | 0x8;
    
        return v.toString(16);
      });
    }
    
    
    // 生成唯一身份标识
    function buildViewID() {
      return Date.now().toString(36) + (Math.ceil(Math.random()*1000)).toString(16);// 最大进制支持转为36进制，使用字符是0-9a-z;
    }
    
    function enBase64(u8a) {
      u8a=new TextEncoder().encode(u8a);
      var maxargs = 0x1000;
      var strs = [];
      for (var i = 0, l = u8a.length; i < l; i += maxargs) {
          strs.push(String.fromCharCode.bind(String).apply(null, u8a.subarray(i, i + maxargs)));
      }
      return btoa(strs.join(''));
    }  function traceId() {
      return '00-' +toHex(getRandom(32), 8)+toHex(getRandom(32), 8) +toHex(getRandom(32), 8)+toHex(getRandom(32), 8)+ '-' +toHex(getRandom(32), 8) +toHex(getRandom(32), 8) +'-00'
    }

  var $global = window || {};

  function isDefined(v) {
      return v !== undefined && v !== null
  }
  // 参数code:只能是索引，不能是其他内容，且索引必须是文档可以查到得
  function log(code, force) {
      if (force||(isDefined(window.BonreeAgent)&&isDefined(window.BonreeAgent.isDebuge))||(isDefined(window.BonreeClient)&&isDefined(window.BonreeClient.isDebuge))||0) {
          if (isDefined(window.console)) {
            window.console['$bonree']=true;//$bonree标识用于log-sdk，带有该标识且为true的日志，log-sdk不采集该条日志
            console.log(code);
            window.console['$bonree']=false;
          }
      }
  }

  function extend(to, from) {
      if (to && from) {
          forEachOwn(from, function (v, k) {
              to[k] = v;
          });
      }
      return to
  }

  function isString(f) {
      return typeof f === 'string'
  }

  function isJSON(str) {
      if (isString(str)) {
          try {
              const obj = JSON.parse(str);
              if (typeof obj == 'object' && obj) {
                  return true;
              } else {
                  return false;
              }
          } catch (e) {
              return false;
          }
      }
  }

  function NIL_FN() {}

  function hasOwnProperty(object, property) {
      return object && Object.prototype.hasOwnProperty.call(object, property)
  }
  function isObject(t) {
    return typeof t === 'object'
  }
  function overwrite(to, from) {
      if (to && from) {
          forEachOwn(from, function (v, k) {
              if (hasOwnProperty(to, k)) {
                  to[k] = v;
              }
          });
      }
      return to
  }

  function forEachOwn(datas, fn,callback) {
      if (! isDefined(datas)) {
          return
      }
      for (var key in datas) {
          if (hasOwnProperty(datas, key)) {
              var data = datas[key];
              try {
                  if (fn(data, key) === false) {
                      break
                  }
              } catch (error) {}

          }
      }
      if(callback){callback();}
  }

  function isFunction(f) {
      return typeof f === 'function'
  }

  function isArray(a) {
      return isDefined(a) && (a instanceof Array)
  }

  function forEach(datas, fn,callback) {
      if (isArray(datas)) {
          return forEachArray(datas, fn,callback)
      }
      return forEachOwn(datas, fn,callback)
  }

  function forEachArray(datas, fn,callback) {
      if (! isArray(datas)) {
          return
      }
      for (var i = 0, len = datas.length; i < len; i++) {
          var data = datas[i];
          // try {
          if (fn(data, i) === false) {
              break
          }
          // } catch (error) {
          // }
      }
      if(callback){callback();}
  }

  function bind(fn, ctx) {
      return function () {
          return fn.apply(ctx, arguments)
      }
  }

  function isEmpty(a){
      if (isDefined(a)) {
          if (hasOwnProperty(a, 'length')) {
            return !a.length
          }
          if (hasOwnProperty(a, 'size')) {
            return !a.size
          }
          for (var i in a) {
            if (hasOwnProperty(a, i)) {
              return false
            }
          }
      }
      return true
  }

  function setCookie(key, value, cfg) {
      try {
        var str = key + '=' + value;
        cfg || (cfg = {});
        if (isDefined(cfg.domain)) {
          str += ';domain=' + cfg.domain;
        }
    
        if (isDefined(cfg.path)) {
          str += ';path=' + cfg.path;
        }
    
        if (isDefined(cfg.expires)) {
          if (typeof cfg.expires === 'string') {
            str += ';expires=' + cfg.expires;
          } else {
            str += ';expires=' + cfg.expires.toUTCString();
          }
        }
        document.cookie = str;
        window.sessionStorage&&window.sessionStorage.setItem(key,value);
        window.localStorage&&window.localStorage.setItem(key,value);
      } catch (error) {
        log('C107');
      }
  }

  function getCookie(item) {
      try {
        var cookies = document.cookie.split(/;\s?/);
        if(document.cookie){
          for (var i = 0, len = cookies.length; i < len; i++) {
            let pair = cookies[i].split('=');
            let key = pair[0];
            let value = pair[1];
            if (key === item) {
              // return value.replace(/['"]/g, '')
              if(isDefined(value)){
                return value
              }
            }
          }
        }
        const value=getSession(item)||'';
        return value
      } catch (error) {
        log('C108');
        return '';
      }
  }

  function getSession(key){
      let value='';
      if(window.sessionStorage){
        value=window.sessionStorage.getItem(key)||'';
        if(isDefined(value)&&value!=""){
          return value
        }
      }
      value=getLocaStore(key)||'';
      return value
  }

  function getLocaStore(key){
      let value='';
      if(window.localStorage){
        value=window.localStorage.getItem(key)||'';
      }
      return value
  }
  function isReadable(v) {
      return isDefined(v) && !isEmpty(v)
  }

  function dateNow() {
      return Date.now ? Date.now() : (new Date()).getTime()
  }
    
    /*
    * 闭包-state为getTime函数执行的时间，
    * 如果在浏览器环境返回的数组元素一为performance.now(),
    * 元素二加上navigationStart(加载起始时间)，参数为0，则返回数组为[0,0+navigationStart]；参数不为0则返回数组[当前时间,当前时间+navigationStart]
    * 非浏览器环境，参数为0 返回[0,初始化state],参数不为0，返回[当前时间-初始化state，当前时间]
    * 另：经过代码梳理，当前项目并未发现传参使用情况
    */
    
  var nowtime = (function () {
      var start = dateNow();
      return function (n) {
        var moment;
        if (isDefined($global.performance) && isDefined($global.performance.now) && isDefined($global.performance.timing)) {
          moment = n === 0 ? 0 : (Math.round($global.performance.now()));
          return [moment * 1000, (moment + ($global.performance.timing.navigationStart)) * 1000]
        }
    
        moment = n === 0 ? start : dateNow();
        return [(moment - start) * 1000, moment * 1000]
      }
  })();
    
  function now(n) {
      return nowtime(n)[1]
  }
  function tillNow(n) {
      return nowtime(n)[0]
  }
  // 获取两个时间值，ps：并无参数传递给nowtime函数
  function getTime() {
      var time = nowtime();
      return {
        startTime: time[0],
        timestamp: time[1]
      }
  }

  function args(i){
    if(!isDefined(i.length)){
      return i
    }
    return Array.prototype.slice.call(i)
  }

  function map(da,fn){
    var r = [];
    forEach(da, function (i, it) {
      var item = fn && fn(i, it);
      if (isDefined(item)) {
        r.push(item);
      }
    });
    return r
  }
  /*network模块用到*/
  /*取object属性值的整数*/
  var getFixedMetric = function (item, metric) {
    var target = item[metric];
    if (isDefined(target) && target > 0) {
      return Math.round(target)
    }

    return 0
  };
  /*根据content类型获取大小*/
  var getContentSize = function (content) {
    if (!isDefined(content)) {
      return 0
    }

    if (window.ArrayBuffer && content instanceof ArrayBuffer) {
      return content.byteLength
    }

    /* global Blob */
    if (window.Blob && content instanceof Blob) {
      return content.size
    }

    if (content.toJSON) {
      return stringify(content.toJSON()).length
    }

    if (content.length) {
      return content.length
    }

    return 0
  };
  /*根据请求体不同获取返回序列化请求体*/
  var getRequestParam = function (c) {
    if (!isDefined(c)) {
      return ''
    }

    var param = '';
    if (typeof c === 'string') {
      param = c;
    } else if (window.FormData && c instanceof FormData) { /* global FormData */
      var formData = {};
      try {
        forEach(iterate(c.entries()), function (ent) {
          var key = ent[0];
          var val = ent[1];
          if (window.File && val instanceof File) { /* global File */
            if (val.size > 0) {
              var txt = val.name ? ' ' + val.name : '';
              formData[key] = '[File]' + txt;
            }
          } else {
            formData[key] = val;
          }
        });
      } catch (ee) {
        formData = {};
        log('C145');
      }
      param = '[FormData] ' + stringify(formData);
    } else if (window.Blob && c instanceof Blob) {
      return '[Blob]'
    } else if (window.ArrayBuffer && c instanceof ArrayBuffer) {

      return '[ArrayBuffer]'
    } else if (c.toJSON) {

      param = stringify(c.toJSON());
    } else if (c.toString) {

      param = c.toString();
    } else {
      return '[unknown]'
    }

    return withLength(param, 2000)
  };
  function getIP(url) {
    if (url) {
      url=url.split("?")[0];
      var rez = /(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\:([0-9]{1,5})/;
      if (rez.test(url)) {
        return [`${RegExp.$1}.${RegExp.$2}.${RegExp.$3}.${RegExp.$4}`,Number(RegExp.$5)]
      } else if (/\:([0-9]{1,5})/.test(url)) {
        return ['', Number(RegExp.$1)]
      } else if (url.indexOf('https') > -1) {
        return ['', 443]
      } else {
        return ['',80]
      }
    }
    return ['','']
  }

  function getUrl$1(path='') {
    // ajax和fetch发送请求的接口，没有路径的情况下给配置上当前网址的域名，如果有域名则返回原值
    if(window.location.protocol==="file:"&&!startWith(path,'http')){
      if(!path){
        // path为空时拼接
        return window&&window.location.href+path
      }
      return path
    }
    if (isDefined(path) && path.indexOf('http')===0) {
      return path
    } else if (/^\/{2}/.test(path)) {
      return window && window.location.protocol+path||'http:'+path
    } else if (/^\?/.test(path)) {
      return window && window.location.origin + window.location.pathname + path || path;
    } else if (/^\/{1}/.test(path)) {
      return  window&&window.location.origin+path ||path
    }else if(/^\.{1,}/.test(path)){
      return window&&window.location.origin+path.replace(/^(\.{1,}\/){1,}/,'/') ||path;
    }else if (isDefined(path)) {
      return  window&&window.location.origin+'/'+path ||path
    }
    return path
  }
  var stringify = isDefined($global.JSON) ? $global.JSON.stringify : function (data) {
    var type = typeof data;
    var str;
    if (type === 'undefined') {
      return '"undefined"'
    }

    if (type === 'boolean') {
      return data ? 'true' : 'false'
    }

    if (type === 'number') {
      return data.toString()
    }

    if (type === 'string') {
      str = data.replace(/(["\\])/g, '\\$1')
        .replace(/\r/g, '\\r')
        .replace(/\n/g, '\\n');
      return '"' + str + '"'
    }

    if (type === 'object') {
      if (!data) {
        return 'null'
      }

      if (data instanceof Array) {
        str = '[';
        forEach(data, function (s, i) {
          if (i > 0) {
            str += ',';
          }
          str += stringify(s);
        });
        str += ']';
        return str
      }

      str = '{';
      var dot = 0;
      forEachOwn(data, function (s, k) {
        if (dot > 0) {
          str += ',';
        }
        str += stringify(k) + ':' + stringify(s);
        dot++;
      });
      str += '}';
      return str
    }

    return '[none]'
  };


  function addListener(ctx, evt, handler, captured) {
    if (ctx && ctx.addEventListener) {
      ctx.addEventListener(evt, handler, captured);
    }
  }
  /*等同addListener*/
  function on$1(ctx, evt, handler, captured) {
    if (ctx && ctx.addEventListener) {
      return ctx.addEventListener(evt, handler, captured)
    }

    if (ctx && ctx.attachEvent) {
      ctx.attachEvent('on' + evt, handler);
    }
  }
  function delay(fn, d) {
    fn.$$original = true;
    return setTimeout(fn, isDefined(d) ? d : 0)
  }

  function last(a) {
    if (isArray(a) && !isEmpty(a)) {
      var len = a.length;
      return a[len - 1]
    }
  }
  var unicode =function (str) {
    var rs = "";
    for (var i = 0; i < str.length; i++) {
        //补零。不补有些库无法正常解析。保持4位
        //slice负数参数，与其方向相反。start=-1为最后一个元素，end=-1为第一个元素。start必须
        rs += "\\u" + ("0000" + str.charCodeAt(i).toString(16)).slice(-4);
    }
    return rs;
  };
  /**
  *对接口的hook包装
  *@param {Function} fn-原始方法
  *@param {Function} before-回调原始前调用方法
  *@param {Function} after-回调调用后调用方法
  *@param {Function} errorHandler-js错误处理
  *@return {Function} 返回包装方法
  **/
  var hack = function (fn, before, after, errorHandler) {
    var exception = function (e) {
      if(isDefined(window.console)){
        window.console['$bonree']=true;
        var errlog=isDefined(window.console.error)?window.console.error(e):NIL_FN;
        errlog(e);
        window.console['$bonree']=false;
      }
    };
    if (!isDefined(fn)) {
      fn = function () { };
    }
    // 已经执行过hack操作
    if (fn.$$original) {
      return fn
    }

    var hackedFn = function () {
      //to array
      var params = args(arguments);
      try {
        // 执行befor fun
        if (isDefined(before)) {
          before.apply(this, params);
        }
        
        return fn.apply(this, params)
      } catch (e) {
        // 报错fun
        if (isDefined(errorHandler)) {
          errorHandler.apply(this, params.concat(e));
        } else {
          exception(e);
        }
      } finally {
        // after fun
        if (isDefined(after)) {
          after.apply(this, params);
        }
        if(params&&params[0]&&params[0] instanceof Error&&fn && fn.name !== 'error'){
          throw(params[0])
        }
      }
    };
    hackedFn.$$original = fn;

    return hackedFn
  };
  /**
  *获取targrt的xpath
  *@param {object}element-需获取xpath的元素
  *@return {String} xpath字符串
  **/
  var xpath = function (element) {
    if (!element) {
      return ''
    }

    var id = element.id;
    if (id) {
      return '//*[@id="' + id + '"]'
    }

    var paths = [];
    var curElement = element;
    while (curElement) {
      var tag = curElement.tagName&&curElement.tagName.toLowerCase&&curElement.tagName.toLowerCase()||null;
      if(!tag){break}
      // var parentElement =curElement.parentElement&&curElement.parentElement.cloneNode(curElement.parentElement);
      // cloneNode 在客户项目中出现自动二次加载图片验证码的情况
      var parentElement =curElement.parentElement&&curElement.parentElement||null;
      if (!isDefined(parentElement)) {
        paths.unshift(tag);
        break
      }

      var brothers = parentElement.children;
      var len = brothers.length;
      var pos = 0;
      var cousin = 0;
      for (var e = 0; e < len; e++) {
        var item = brothers[e];
        if (item.tagName.toLowerCase() === tag) {
          cousin++;

          if (pos > 0) {
            break
          }
        }

        if (item === curElement) {
          pos = cousin;
        }
      }

      if (cousin === 1) {
        paths.unshift(tag);
      } else {
        paths.unshift(tag + '[' + pos + ']');
      }
      curElement = parentElement;
    }
    return '/' + paths.join('/')
  };
  /**
  *返回object某属性值,没有该属性返回null
  *@param {any} obj
  *@param {String} key
  *@return {boolean} 
  **/
  var prop = function (obj, key) {
    if (isDefined(obj) && hasOwnProperty(obj, key)) {
      return obj[key]
    }

    return null
  };
  /** 
  *代替原生方法解决兼容问题
  *@param {Array} haystack-被判断数组/字符串
  *@param {any} needle-需判断子元素
  *@return {boolean} 是否包含子元素结果
  **/
  function includes(haystack, needle){
    for (let i = 0, l = haystack.length; i < l; ++i) {
      if (haystack[i] === needle) {
        return true
      }
    }
    return false
  }
  /**
  *判断参数是否是object
  *@param {any} t-被判断参数
  **/
  function isObj (t) {
    return typeof t === 'object'
  }
  /**
  *获取userAgent信息
  *@return {object}
  **/
  function getUserAgent(){
    try {
    let browserReg = {
        Chrome: /Chrome/,
        IE: /MSIE/,
        Firefox: /Firefox/,
        Opera: /Presto/,
        Safari: /Version\/([\d.]+).*Safari/,
        '360': /360SE/,
        QQBrowswe: /QQ/,
      };
      
      let deviceReg= {
        iPhone: /iPhone/,
        iPad: /iPad/,
        Android: /Android/,
        Windows: /Windows/,
        Mac: /Macintosh/,
      };
    let userAgentStr =navigator&&navigator.userAgent;
    if(!userAgentStr){
      return null
    }
    const userAgentObj = {
      browserName: '',    // 浏览器名称
      browserVersion: '', // 浏览器版本
      osName: '',         // 操作系统名称
      osVersion: '',      // 操作系统版本
      deviceName: '',     // 设备名称
    };

    for(let key in browserReg) {
      if(browserReg[key].test(userAgentStr)) {
        userAgentObj.browserName = key;
        if(key === 'Chrome') {
          userAgentObj.browserVersion = userAgentStr.split('Chrome/')[1].split(' ')[0];
        } else if(key === 'IE') {
          userAgentObj.browserVersion = userAgentStr.split('MSIE ')[1].split(' ')[1];
        } else if(key === 'Firefox') {
          userAgentObj.browserVersion = userAgentStr.split('Firefox/')[1];
        } else if(key === 'Opera') {
          userAgentObj.browserVersion = userAgentStr.split('Version/')[1];
        } else if(key === 'Safari') {
          userAgentObj.browserVersion = userAgentStr.split('Version/')[1].split(' ')[0];
        } else if(key === '360') {
          userAgentObj.browserVersion = '';
        } else if(key === 'QQBrowswe') {
          userAgentObj.browserVersion = userAgentStr.split('Version/')[1].split(' ')[0];
        }
      }
    }

    for(let key in deviceReg){
      if(deviceReg[key].test(userAgentStr)){
        userAgentObj.osName = key;
        if(key === 'Windows'){
          userAgentObj.osVersion = userAgentStr.split('Windows NT ')[1].split(';')[0];
        } else if(key === 'Mac') {
          userAgentObj.osVersion = userAgentStr.split('Mac OS X ')[1].split(')')[0];
        } else if(key === 'iPhone') {
          userAgentObj.osVersion = userAgentStr.split('iPhone OS ')[1].split(' ')[0];
        } else if(key === 'iPad') {
          userAgentObj.osVersion = userAgentStr.split('iPad; CPU OS ')[1].split(' ')[0];
        } else if(key === 'Android') {
          userAgentObj.osVersion = userAgentStr.split('Android ')[1].split(';')[0];
          userAgentObj.deviceName = userAgentStr.split('(Linux; Android ')[1].split('; ')[1].split(' Build')[0];
        }
      }
    }
    return userAgentObj
  } catch (error) {
      log('C123');
      return undefined
  }
  }
  /**
  *对对象obj指定长度截取
  *@param {object} obj-被截取对象
  *@param {Number} num-截取长度
  *@return {object} 截取结果
  **/
  function getElementForNum(obj,num){
    if(!isObj(obj)){
        return {}
    }
    var newData = {};
    let newKeys = Object.keys(obj);
    newKeys.map((item,idx)=>{
        if(idx <= num){
        newData[item] = obj[item];
        }
    });
    return newData
  }
  /**
   * @descripe 将可迭代对象迭代后放入数组
   * @param {object} iter 可迭代对象
   **/
  function iterate(iter) {
    var data = [];
    if (!isDefined(iter) || !isDefined(iter.next)) {
      return data
    }

    var item = iter.next();
    while (!item.done) {
      data.push(item.value);
      item = iter.next();
    }
    return data
  }
  /**
   * @descripe 从流中读取byte大小
   * @param {*} stream 数据流
   * @param {*} options 读取配置
   * @param {*} callback 回调
   **/
  function readBytesFromStream(stream, options, callback) {
    if (!stream.getReader) {
        return 0
    }
    const reader = stream.getReader();
    const chunks = [];
    let readBytesCount = 0;
    readMore();
    function readMore() {
        reader.read().then(
            (result) => {
                if (result.done) {
                    let size = onDone();
                    callback(size);
                    return
                }
                
                {
                    chunks.push(result.value);
                }
                readBytesCount += result.value.length;
                if (readBytesCount > options.bytesLimit) {
                    let size = onDone();
                    callback(size);
                } else {
                    readMore();
                }
            }
        );
    }

    function onDone() {
        reader.cancel().catch(
            // we don't care if cancel fails, but we still need to catch the error to avoid reporting it
            // as an unhandled rejection
            noop
        );
        let bytes;
        {
            let completeBuffer;
            if (chunks.length === 1) {
                // optimization: if the response is small enough to fit in a single buffer (provided by the browser), just
                // use it directly.
                completeBuffer = chunks[0];
            } else {
                // else, we need to copy buffers into a larger buffer to concatenate them.
                completeBuffer = new Uint8Array(readBytesCount);
                let offset = 0;
                chunks.forEach((chunk) => {
                    completeBuffer.set(chunk, offset);
                    offset += chunk.length;
                });
            }
            bytes = completeBuffer.slice(0, options.bytesLimit);
            completeBuffer.length > options.bytesLimit;
            return bytes.length
        }
    }
  }
  function noop() {}
  /**
   * @descripe 尝试从response复制clone
   * @param {object} response 响应内容
   * @return clone的响应体流
   **/
  function tryToClone(response){
    try {
      return response.clone()
    } catch (e) {
      // clone can throw if the response has already been used by another instrumentation or is disturbed
      return
    }
  }
  /** 
   * @descripe 控制对象键值对数
   * @param {*} data 被控制对象
   * @param {*} emit 控制的键值对数
   * @return 截取后的对象
   **/
  function set_64_keys(data, emit) {
    var reData = {};

    if (!isDefined(data)) {
      return reData;
    } else {
      if (typeof (data) == 'string' && data!=='') {
          data = eval('(' + data + ')');
          if (isJSON(data)) {
              data = JSON.parse(data);
          } else {
              return data
          }
      }
      if (typeof (data) != 'object') {
        return data
      }

      var keys = Object.keys(data);

      if (keys.length > emit) {
        keys = keys.slice(0, emit);
        keys.forEach(function (item) {
          reData[item] = data[item];
        });
        return reData;
      }
      return data
    }
  }
  /**
   * @descripe 对数组filter
   * @param {*} datas 需处理数组
   * @param {*} fn 回调函数
   * @return 处理后的数组
   **/
  function filter(datas, fn) {
    var ret = [];
    forEach(datas, function (i, iter) {
      if (fn && fn(i, iter) === true) {
        ret.push(i);
      }
    });
    return ret
  }
  // 在bonreeRUM上挂载deviceId，供log-sdk使用
  function setDeviceForLog(deviceId){
    if(window.bonreeRUM && deviceId){
      window.bonreeRUM['fingerId']=deviceId;
    }
  }
  // 
  function size(t) {
    if (!t) {
      return 0
    }
    if (typeof t === 'string') {
      const len = strSize(t);
      return len
    }
    // if (t.length) {
    //   return t.length
    // }
    if (t instanceof ArrayBuffer) {
      return t.byteLength
    }
    if (isObject(t)) {
      let tmp = '';
      try {
        tmp = JSON.stringify(t);
      } catch (err) {}
      const len = strSize(tmp);
      return len
    }
    return 0
  }
  function strSize(str) {
    let total = 0;
    for (let i = 0, j = str.length; i < j; i++) {
      const charCode = str.charCodeAt(i);
      if (charCode <= 0x007f) {
        total += 1;
      } else if (charCode <= 0x07ff) {
        total += 2;
      } else if (charCode <= 0xffff) {
        total += 3;
      } else {
        total += 4;
      }
    }
    return total
  }

  function trim(t) {
    if (t) {
      return String.prototype.trim
        ? String.prototype.trim.call(t) : t.toString().replace(/(^\s+)|(\s+$)/g, '')
    }

    return ''
  }

  function startWith(s, t) {
    return s && s.indexOf ? s.indexOf(t) === 0 : false
  }

  function endWith(s, t) {
    if(areUrlsEqual(s,t)){
      return true
    }
    if (s && t && s.length >= t.length) {
      if(s.slice(-1)==="/"){
        t=t+'/';
      }
      return s.substring(s.length - t.length) === t
    }

    return false
  }

  function areUrlsEqual(url1, url2) {
    try {
      // 使用 URL 对象来解析 URL
      const parsedUrl1 = new URL(url1);
      const parsedUrl2 = new URL(url2);

      // 比较协议、主机、路径和查询参数
      if (
          parsedUrl1.protocol === parsedUrl2.protocol &&
          parsedUrl1.host === parsedUrl2.host &&
          parsedUrl1.pathname === parsedUrl2.pathname &&
          parsedUrl1.search === parsedUrl2.search &&
          parsedUrl1.hash===parsedUrl2.hash
      ) {
          return true;
      } else {
          return false;
      }    
    } catch (error) {
        return false
    }
  }

  function withLength(str, len) {
    try {
      if (!str) {
        return ''
      }
      if (str.length <= len) {
        return str
      }
      return str.substr(0, len - 3) + '...'
    } catch (error) {
      return "The data cannot be parsed normally, please handle it manually"
    }
  }

  function toUpper(s, dv) {
    if (!isDefined(dv)) {
      dv = '';
    }

    return s && s.toUpperCase ? s.toUpperCase() : dv
  }

  function toLower(s, dv) {
    if (!isDefined(dv)) {
      dv = '';
    }

    return s && s.toLowerCase ? s.toLowerCase() : dv
  }

  var stringify = isDefined(window.JSON) ? window.JSON.stringify : function (data) {
      var type = typeof data;
      var str;
      if (type === 'undefined') {
        return '"undefined"'
      }
    
      if (type === 'boolean') {
        return data ? 'true' : 'false'
      }
    
      if (type === 'number') {
        return data.toString()
      }
    
      if (type === 'string') {
        str = data.replace(/(["\\])/g, '\\$1')
          .replace(/\r/g, '\\r')
          .replace(/\n/g, '\\n');
        return '"' + str + '"'
      }
    
      if (type === 'object') {
        if (!data) {
          return 'null'
        }
    
        if (data instanceof Array) {
          str = '[';
          forEach(data, function (s, i) {
            if (i > 0) {
              str += ',';
            }
            str += stringify(s);
          });
          str += ']';
          return str
        }
    
        str = '{';
        var dot = 0;
        forEachOwn(data, function (s, k) {
          if (dot > 0) {
            str += ',';
          }
          str += stringify(k) + ':' + stringify(s);
          dot++;
        });
        str += '}';
        return str
      }
    
      return '[none]'
  };

  function toString$2(data){
      if(typeof data ==='string'){
        return data
      }
      let str=JSON.stringify(data);
      return str
    }

  function set_length(str, num) {
      if (!str) {
          return str;
      }
      if (str.length > num) {
          return str.slice(0,num)
      }
      return str
  }

  function getDataSize(str,limit) {
    // 使用UTF-8编码计算字符串的字节长度
    if(typeof str!=="string"){
      str=JSON.stringify(str);
    }
    let totalBytes = new Blob([str]).size;
    
    // 将字节长度转换为兆字节（MB）
    let sizeInMB = totalBytes / (1024 * 1024);
    if(isDefined(limit)){
      if(sizeInMB<limit){
        return true
      }
      return false
    }
    // 返回结果
    return sizeInMB;
  }

  const GC = {
      BROWSER: 0,
      ANDROID: 1,
      IOS: 2,
      WINDOWS: 3,
      HOS: 4,
      ZERO: 0,
      THOUSAND: 1000,
      TYPEARR: ['', 'android', 'ios', 'pc'],
      FLUSH_DATA:'data/flush',
      PAGE_READY:'page/ready',
      PAGE_LOAD:'page/load',
      PAGE_DATA:'data/page',
      RESOURCE_DATA:'data/resource',
      CONSOLE_DATA:'data/console',
      TITLE:"title",
      DURATION:'duration',
      NAVIGATION_START :'navigationStart',
      FETCH_START : 'fetchStart',
      START_TIME : 'startTime',
      UNLOAD_EVENT_START : 'unloadEventStart',
      UNLOAD_EVENT_END : 'unloadEventEnd',
      REDIRECT_START : 'redirectStart',
      REDIRECT_END : 'redirectEnd',
      DOMAIN_LOOKUP_START : 'domainLookupStart',
      DOMAIN_LOOKUP_END : 'domainLookupEnd',
      CONNECT_START : 'connectStart',
      CONNECT_END : 'connectEnd',
      SECURE_CONNECTION_START : 'secureConnectionStart',
      REQUEST_START : 'requestStart',
      RESPONSE_START : 'responseStart',
      RESPONSE_END : 'responseEnd',
      RESPONSE_STATUS:'responseStatus',
      DOM_LOADING : 'domLoading',
      DOM_INTERACTIVE : 'domInteractive',
      DOM_CONTENT_LOADED_EVENT_START : 'domContentLoadedEventStart',
      DOM_CONTENT_LOADED_EVENT_END : 'domContentLoadedEventEnd',
      DOM_COMPLETE : 'domComplete',
      LOAD_EVENT_START : 'loadEventStart',
      LOAD_EVENT_END : 'loadEventEnd',
      FIRST_PAINT : 'fp',
      FIRST_CONTENTFUL_PAINT : 'fcp',
      LARGEST_CONTENTFUL_PAINT : 'lcp',
      REDIRECT_COUNT : 'redirectCount',
      WORKER_START : 'workerStart',
      NEXT_HOP_PROTOCOL : 'nextHopProtocol',
      TRANSFER_SIZE : 'transferSize',
      ENCODED_BODY_SIZE : 'encodedBodySize',
      DECODED_BODY_SIZE : 'decodedBodySize',
      UPLOAD_BODY_SIZE : 'uploadBodySize',
      REQUEST_HEADER : 'requestHeader',
      RESPONSE_HEADER : 'responseHeader',
      CALLBACK_START : 'callbackStart',
      CALLBACK_END : 'callbackEnd',
      CALLBACK_TIME : 'callbackTime',
      USER_TIME : 'userTime',
      TIMESTAMP : 'timestamp',
      INITIATOR_TYPE : 'initiatorType',
      XML_HTTP_REQUEST : 'xmlhttprequest',
      FETCH : 'fetch',
      TAG_NAME : 'tagName',
      TYPE : 'type',
      MODEL : 'model',
      EMBED : 'embed',
      IS_MAIN_DOCUMENT : 'isMainDocument',
      PAGE_ID : 'pageViewId',
      PAGE_URL : 'pageUrl',
      PAGE_TITLE : 'pageTitle',
      MESSAGE : 'message',
      NAME : 'name',
      ERROR_LINE : 'line',
      ERROR_FILE : 'file',
      ERROR_COLUMN : 'column',
      ERROR_STACK : 'stack',
      JS_ERROR : 'jsError',
      IS_SLOW : 'isSlow',
      IS_CUSTOM : 'isCustome',
      URL : 'url',
      NET_METHOD : 'method',
      NET_PORT : 'port',
      NET_IP : 'ip',
      NET_DT : 'domainLookupTime',
      NET_CT : 'connectTime',
      NET_SSLT : 'ssl',
      NET_DTI : 'downloadTime',
      NET_CNA : 'cname',
      NET_PT : 'protocalType',
      NET_TID : 'guid',
      NET_XBR : "xBrResponse",
      NET_TRACE : "traceResponse",
      NET_TPAR : "tpar",
      NET_EOP : 'errorOccurrentProcess',
      NET_EC : 'code',
      NET_TYPE : 'requestType',
      NET_RET : 'resourceType',
      CUSTOM_IC : 'customIc',
      NET_CBBQ : 'requestBodyByKey',
      REQUEST_BODY : 'requestBody',
      NET_CBHQ : 'requestHeaderByKey',
      NET_CBQ : 'reqUrlDta',
      REQUEST_HEADER_ALL : 'requestHeaderAll',
      E_TYPE : 'eType',
      UA : 'userAgent',
      SOURCE_OF_ACTION : 'sourceOfAction',
      FRAME_TYPE : 'frameType',
      STAY_TIME : 'stayTime',
      CORRELATION_ID : 'correlationId',
      IS_EXIT : 'isExit',
      PAGE_CREATE_TIME : 'pageCreateTime',
      REFERRER : 'referrer',
      STATUS : 'status',
      STATUS_TEXT:'statusText',
      ALIAS : 'alias',
      PATH : 'path',
      ROOT : 'root',
      FULL_URL : 'fullUrl',
      FRAME_WORK : 'framework',
      CLIENT_TYPE : 'clientType',
      VALUE:"value",
      FULL_RESOURCE_LOAD_TIME:'fullResourceLoadTime',
      PAGE_INVISIBLE : 'page/invisible',
      PAGE_VISIBLE : 'page/visible',
      RESOURCE_DUMP : 'resource/dump',
      ERROR_DATA : 'data/error',
      REQUEST_INIT : 'request/init',
      REQUEST_DATA : 'data/request',
      ROUTE_DATA : 'data/route',
      ACTION_DATA : 'data/event',
      TRACE_ACTION_DATA:'data/traceAction',
      SESSION_CHANGE : 'session/change',
      USER_SET : 'user/set',
      PARAM:'param',
      SPAN_DATA:'data/span',
      FULLY_COLLECT : 1000,
      NET : 'network',
      VIEW : 'view',
      ERROR : 'jserror',
      ACTION : 'action',
      ROUTE : 'routechange',
      WEBVIEWDATA : 'h5',
      PAGE : 'page',
      RESOURCE : 'resource',
      CUSTOM_EVENT : 'customevent',
      CUSTOM_METRIC : 'custommetric',
      CUSTOM_LOG : 'customlog',
      CRASH : 'crash',
      SPEED_TEST : 'speedtest',
      CONSOLE:'console',
      SPAN :'span',
      GUID_KEY:'br-resp-key',
      X_BR_RESPONSE:"x-br-response",
      TRACE_RESPONSE:"traceresponse",
      LIFESTYLE_XHR_START:"XMLHttpRequest_Start",
      LIFESTYLE_REQUEST_END:"Request_Completed",
      LIFESTYLE_FETCH_START:"FETCH_Satrt",
      CUSTOM_ACTION_END:"customActionEnd",
      INIT_SESSION_START:"initSessionStart",
      LIFESTYLE_CALLBACK_REQUEST_START:"CallbackRequest_Start",
      ROUTE_CHANGE_START:"ROUTE_CHANGE_START",
      ROUTE_CHANGE_END:"ROUTE_CHANGE_END",
      SPAN_CALLBACK_DATA:"SPAN_CALLBACK_DATA",
      WEBSOCKET_CONNECTION_START:"WEBSOCKET_CONNECTION_START",
      WEBSOCKET_CONNECTION_END:"WEBSOCKET_CONNECTION_END",
      XHR_CALLBACK_IDENTIFY:"XHR_CALLBACK_IDENTIFY"
  };

  /*
  * 通过下发的配置，动态获取userId
  * 1.直接配置userId，则不启动动态获取userId的模块，直接配置优先级最高
  * 2.后期通过API接口配置的会覆盖直接配置的，此时优先级最高的是通过配置的userId
  * 3.根据下发配置，进行数据采集及数据的更新，最后是上报
  * // 注释：配置下发，根据数组的顺序既定数据采集的权重
  * // 除下发配置外，自定义用户id配置，且权重最高
  *    userdefine:[
  *        {   type:"1", // 1:css,2:javascript var ,3:meta tag ,4:cookie ,5:querystring ,6:request header,7:response header
  *            rule:"#userId"},
  *        {   type:"2", // 2 ：变量
  *            rule:"a.b.c"},
  *        {   type:"3", // 3: met标签
  *            rule:"userId"},
  *        {   type:"4", // 4: cookie
  *            rule:"userId"},
  *        {   type:"5", // 5: querystring
  *            rule:"userId"},
  *        {   type:"6",//request header
  *            rule:"userId"},
  *        {   type:"7", // response header
  *             rule:"userId"}
  *    ]
  * code for qiuyuan
  */


  function checkValue(val) {
      if (!isDefined(val) || val instanceof Object) {
          return false
      }
      if (!isString(val)) {
          val = "" + val;
      }
      if (/^[\u4E00-\u9FFFa-zA-Z0-9:_\-@.\s/]+$/.test(val) && val.length<=256){
          return true
      }
      return false
  }

  class getUserIdManage{
      constructor(){
          this.useAPI=false; // false走配置，true关闭配置采集，直接配置userID和使用api的时候值为true
          this.configeManage=[]; // 当前配置配合下发配置使用，获取到配置的时候会进行一次数据重置，采集到数据后会再次进行数据重置，会进行多次数据重置
          this.originManageData=null;
          this.cookieArr=[];
          this.requestArr=[];
          this.responseArr=[];
          this.isStopGetValue=50;
      }

      checkOriginManageData(data){
          // 限制长度
          if(this.useAPI){
              return
          }
          data=data&&isString(data)&& JSON.parse(data)||data;
          if(isDefined(data)&&Array.isArray(data)){
              this.originManageData=data;
              if(data.length> 50) {
                  this.configeManage = data.slice(0, 50); // 这里50是开发定义的，后期可以调整
              } else {
                  this.configeManage = data;
              }
               this.startCatchDataFun();
          }
      }

      startCatchDataFun() {
          for (let i = 0, j = this.configeManage.length - 1; i <= j; i++) {
              if (this.configeManage[i] && this.configeManage[i]['type']) {
                  switch (this.configeManage[i]['type']) {
                      case 1:
                          let data = this.getDataWithType_1(this.configeManage[i]['rule']);
                          if(isDefined(data)){
                              setCookie("login_username",data);
                          }
                          this.configeManage[i]['value'] = data;
                          break;
                      case 2:
                          this.configeManage[i]['value'] = this.getDataWithType_2(this.configeManage[i]['rule']);
                          break;
                      case 3:
                          this.configeManage[i]['value'] = this.getDataWithType_3(this.configeManage[i]['rule']);
                          break;
                      case 4:
                          // this.configeManage[i]['value']=
                          this.getDataWithType_4(this.configeManage[i]['rule'], i);
                          break;
                      case 5:
                          this.configeManage[i]['value'] = this.getDataWithType_5(this.configeManage[i]['rule']);
                          break;
                      case 6:
                          // this.configeManage[i]['value']=
                          this.getDataWithType_6(this.configeManage[i]['rule'], i);
                          break;
                      case 7:
                          // this.configeManage[i]['value']=
                          this.getDataWithType_7(this.configeManage[i]['rule'], i);
                          break;
                  }
              }
          }
          getCookieUserID$1();
          this.checkValueRight();
      }

      checkValueRight() {
          for (let i = 0, j = this.configeManage.length - 1; i <= j; i++) {
              if (isDefined(this.configeManage[i]) && isDefined(this.configeManage[i]["value"])) {
                  this.isStopGetValue = i;
                  globalData.configUser(this.configeManage[i]["value"], true);
                  return
              }
          }
      }

      getDataWithType_1(data) {
          if (data && data.length > 256) {
              return undefined
          }
          try {
              if (data && data.indexOf("@") > 0) {
                  let arr = data.split("@");
                  let tag = document && document.querySelector(arr[0]) || null;
                  if (tag && tag[arr[1]]) {
                      if (checkValue(tag[arr[1]])) {
                          return tag[arr[1]]
                      }
                  }
              } else {
                  let tag = document && document.querySelector(data) || null;
                  if (tag && checkValue(tag.innerText)) {
                      return tag.innerText;
                  }
              }
          } catch (error) {
              log("C138");
          }
          return undefined
      }

      getDataWithType_2(data) {
          if (data && data.length > 256) {
              return undefined
          }
          if (isDefined(data)) {
              if (data.indexOf(".") != -1) {
                  let arr = data.split(".");
                  let tag;
                  arr.map(function (item, index) {
                      tag = tag && tag[item] || (index == 0 && window[item]) || undefined;
                  });
                  if (tag && checkValue(tag)) {
                      if (isString(tag)) {
                          return tag
                      } else {
                          return "" + tag
                      }
                  }
              } else if (checkValue(window[data])) {
                  return "" + window[data]
              }
          }
          return undefined
      }

      getDataWithType_3(data) {
          if (data && data.length > 256) {
              return undefined
          }
          try {
              let val = document.head.querySelector(`[name~=${data}][content]`).content;
              if (isDefined(val) && checkValue(val)) {
                  return val
              }
          } catch (error) {
              log("C139");
          }
          return undefined
      }

      getDataWithType_4(data, index) {
          if (data && data.length > 256) {
              return undefined
          }
          this.cookieArr.push({"rule": data, "index": index});
      }

      getDataWithType_5(data) {
          try {
              if (data && data.length > 256) {
                  return undefined
              }
              if (window && window.location && window.location.search) {
                  let url = decodeURI(window.location.search);
                  let arr = url.split("?")[1].split("&");
                  for (let i of arr) {
                      if (i.split("=")[0] == data) {
                          if (checkValue(i.split("=")[1])) {
                              return i.split("=")[1]
                          }
                      }
                  }
              }
          } catch (error) {
              log("C140");
          }
          return undefined
      }

      getDataWithType_6(data, index) {
          if (data && data.length > 256) {
              return undefined
          }
          let have = false;
          this.requestArr.map(function (item) {
              if (item.rule == data) {
                  have = true;
              }
          });
          if (! have) {
              this.requestArr.push({"rule": data, "index": index});
          }
      }

      getDataWithType_7(data, index) {
          if (data && data.length > 256) {
              return undefined
          }
          let have = false;
          this.responseArr.map(function (item) {
              if (item.rule == data) {
                  have = true;
              }
          });
          if (! have) {
              this.responseArr.push({"rule": data, "index": index});
          }
      }

      changeUseAPI(data) {
          this.useAPI = data;
      }
  }
  let getUserIdManageClass = new getUserIdManage();

  function getCookieUserID$1(){
      let cookieArr=getUserIdManageClass.cookieArr;
      let configeManage=getUserIdManageClass.configeManage;
      if(cookieArr.length>0){
        for(let i=0,j=cookieArr.length-1;i<=j;i++){
          let da=getCookie(cookieArr[i].rule);
          if(isDefined(da)&&checkValue(da)){
            if(cookieArr[i].index<=getUserIdManageClass.isStopGetValue){
              configeManage[cookieArr[i].index]["value"]=""+da;
              getUserIdManageClass.checkValueRight();
              return
            }
          }
        }
      }
  }

  function Notifier() {
      this.listeners = {};
  }
  extend(Notifier.prototype, { /**
     * on 先判定事件evt和方法listener，如果都存在且合法，若事件不是数组，将事件组装为数组；
     * 循环事件，在listeners对象中以事件名作为键，值为数组，若之前没有值，则赋值一个空数组然后将当前监听执行函数放进去，若有值则直接push添加
    */
      on: function (evt, listener) {
          if (isDefined(evt) && isFunction(listener)) {
              var events = evt;
              if (!isArray(events)) {
                  events = [evt];
              }
              forEach(events, bind(function (e) {
                  var handlers = this.listeners[e];
                  if (!isDefined(handlers)) {
                      handlers = this.listeners[e] = [];
                  }
                  handlers.push(listener);
              }, this));
          }
      },
      /*
    * emit为触发listeners的对应属性的方法的执行，因为对应的键值是数组，所以需要循环执行forEach
     */
      emit: function (action) {
          if (!isDefined(action) || !isDefined(action.t)) {
              return
          }
          var type = action.t;
          var handlers = this.listeners[type];
          forEach(handlers, function (fn) {
              fn(action);
          });
      },
      /*
     * remove为已注册listeners的的移除函数，用于解绑事件的监听处理类的执行
    */
      remove: function (evt) {
          if (!isDefined(evt)) {
              return
          }
          var eventKeys = evt;
          if (!isArray(eventKeys)) {
              eventKeys = [evt];
          }
          // 移除指定类型的事件监听
          forEach(eventKeys, bind(function (key) {
              delete this.listeners[key];
          }, this));
      }
  });

  var notifier = new Notifier();
  var notifierOn = bind(notifier.on, notifier);
  var notifierEmit = bind(notifier.emit, notifier);
  var notifierRemove = bind(notifier.remove, notifier);

  class SessionManager{
      constructor(){
          this.sessionCache='br-session-cache';
          this.current='br-current-appid';
      }
      newAppid(appid){
          if(!isDefined(appid)){
              return 
          }
          const currentSessionCache=this.getCurrentSesssionKey(appid);
          if(getCookie(currentSessionCache)&&this.queryAppid(appid)){
              return
          }else {
              this.currentAppid={appId:appid,sessionID:uuid(),lastVisitedTime:new Date().getTime(),startTime:0};
              if(getCookie(currentSessionCache)){
                  let sessionArr=JSON.parse(getCookie(currentSessionCache));
                  sessionArr.unshift(this.currentAppid);
                  setCookie(currentSessionCache,JSON.stringify(sessionArr),this.getSessionConfig());
              }else {
                  setCookie(currentSessionCache,JSON.stringify([this.currentAppid]),this.getSessionConfig());
              }
          } 
          setCookie(this.current,appid,this.getSessionConfig()); 
      }
      setSessionCookie(key, val) {
          let that=this;
          setCookie(key, val, that.getSessionConfig());
      }
      getSessionConfig(){
          var cookieCfg = {
              path: '/'
          };
      
          if (GS.sett.sessionDomain) {
              cookieCfg.domain = GS.sett.sessionDomain;
          }
          return cookieCfg
      }
      /**
       * @descripe 查询是否存储过,存储过更新(时间/session),未存储过返回fasle
       **/
      queryAppid(appid){
          if(globalData.BonreeRecordState===false&&window.BonreeAgent&&window.BonreeAgent.BonreeRecord){
              window.BonreeAgent.BonreeRecord(GS.sett);
          }
          const currentSessionCache=this.getCurrentSesssionKey(appid);
          let sessionData= getCookie(currentSessionCache);
          var sessionArr=isJSON(sessionData) && JSON.parse(sessionData) || [];
          for(let ele of sessionArr){
          /*appid查询到*/
          if(ele.appId===appid){
              /*超时更新session与最后活跃时间*/
              if(new Date().getTime()-ele.lastVisitedTime>GS.sett.sessionTimeout/1000){
                  GS.setData('isFirstUpload',1);
                  usdManager.initUsdTime();
                  ele.sessionID=uuid();
                  notifierEmit({t:GC.INIT_SESSION_START});
                  try{
                      if(isDefined(window.BonreeRecord)&&isDefined(window.BonreeRecord.BonreeRecord)){
                          window.BonreeRecord.BonreeRecord.takeFullSnapshot();
                      }
                      if(isDefined(window.BonreeAgent)&&isDefined(window.BonreeAgent.BonreeRecord)){
                          window.BonreeAgent.BonreeRecord.takeFullSnapshot();
                      }
                  }catch(err){
                      log("C155");
                  }
                  ele.lastVisitedTime=new Date().getTime();
                  ele.startTime=0;
                  setCookie(currentSessionCache,JSON.stringify(sessionArr),this.getSessionConfig());
                  return ele
              }else {
                  /*未超时更新最后活跃时间*/
                  ele.lastVisitedTime=new Date().getTime();
                  setCookie(currentSessionCache,JSON.stringify(sessionArr),this.getSessionConfig());
                  return ele
              }
          }
          }
          return false
      }
      /**
       * @descripe 设置appid,更新配置
       **/
      setAppid(config){
          GS.setConfig(config,false,0);
          var appid=config.appId;
          if(!isDefined(appid)){
              return
          }
          const currentSessionCache=this.getCurrentSesssionKey(appid);
          if(getCookie(currentSessionCache)){
              if(this.queryAppid(appid)){
                  setCookie(this.current,appid,this.getSessionConfig());
              }else {
                  /*没有设置过appid的情况*/
                  var currentCache=JSON.parse(getCookie(currentSessionCache));
                  GS.setData('isFirstUpload',1);
                  usdManager.initUsdTime();
                  notifierEmit({t:GC.INIT_SESSION_START});
                  this.currentAppid={appId:appid,sessionID:uuid(),lastVisitedTime:new Date().getTime(),startTime:0};
                  try{
                      if(isDefined(window.BonreeRecord)&&isDefined(window.BonreeRecord.BonreeRecord)){
                          window.BonreeRecord.BonreeRecord.takeFullSnapshot();
                      }
                      if(isDefined(window.BonreeAgent)&&isDefined(window.BonreeAgent.BonreeRecord)){
                          window.BonreeAgent.BonreeRecord.takeFullSnapshot();
                      }
                  }catch(err){
                      log("C155");
                  }
                  currentCache.unshift(this.currentAppid);
                  if(currentCache.length>=20){
                      currentCache.pop();
                  }
                  setCookie(currentSessionCache,JSON.stringify(currentCache),this.getSessionConfig());
              }
          }else {
              /*初次嵌入或者清楚了缓存*/
              GS.setData('isFirstUpload',1);
              usdManager.initUsdTime();
              notifierEmit({t:GC.INIT_SESSION_START});
              this.currentAppid={appId:appid,sessionID:uuid(),lastVisitedTime:new Date().getTime(),startTime:0};
              try{
                  if(isDefined(window.BonreeRecord)&&isDefined(window.BonreeRecord.BonreeRecord)){
                      window.BonreeRecord.BonreeRecord.takeFullSnapshot();
                  }
                  if(isDefined(window.BonreeAgent)&&isDefined(window.BonreeAgent.BonreeRecord)){
                      window.BonreeAgent.BonreeRecord.takeFullSnapshot();
                  }
              }catch(err){
                  log("C155");
              }
              const currentSessionCache=this.getCurrentSesssionKey(appid);
              setCookie(currentSessionCache,JSON.stringify([this.currentAppid]),this.getSessionConfig());
          }
          setCookie(this.current,appid,this.getSessionConfig());
      }
      getSession(){
          // var currentAppid=getCookie(this.current)
          return this.queryAppid(GS.sett.appId || GS.secondSett.appId)
      }
      getCurrentSesssionKey(appId){
          return this.sessionCache+'-'+appId
      }
  }

  let sessionM=new SessionManager();

  // osType：0:web,1:android,2:ios,3:windows,4:hos
  // probability： 启动概率，千分制(配置融合以后要计算启动概率)
  // sessionPeriod:微秒30分钟
  // sessionTimeout:微秒5分钟
  // isFirstUpload: 是否是第一包数据上传
  function globalSet() {
      this.sett = {
          osType: GC.BROWSER,
          probability: GC.THOUSAND,
          sessionPeriod: 30 * 60 * 1000000,
          sessionTimeout: 5 * 60 * 1000000,
          sessionEvents: 2000,
          debounce: 1000,
          ignoreRequestParams: false,
          ignoreRequestHeaders: false,
          ignoreResources: false,
          ignoreUserEvents: false,
          isFirstUpload: 1,
          exBrowser: ["Firefox/47"],
          appVersion: '1.0.0',
          agentVersion:version,
          appName: "unKnown",
          appId: '',
          hcs: 1,
          channelId: null,
          deviceId: null,
          pageViewId: uuid(),
          pageUrl: document&&document.URL,
          reqBodyKey: null,
          reqURLKey: null,
          reqHeaderKey: null,
          // uploadAddrHttps: "https://bupload.bonree.com/upload",
          // uploadAddrHttp: "http://bupload.bonree.com/upload",
          userKey: 'br-user',
          isDebuge: false,
          cycleTime:10,//数据上报周期
          useXHR:false,
          maxSize:20,//kb
          enableWebsocket:true,
          ac: {
              ac: true,
              cp: 30,
              // mmd: 5,
              aot: 30000
          },
          traceConfig: {
              urlTotalList: [],
              urlWhiteList: [],
              urlBlackList: []
          }
      };
      this.oriArr = [];
      this.initArr = [];
      this.secondSett={};
  }/**
   * @descripe 设置配置,配置更新
   * @param {object} data 配置
   * @param {boolean} isFirstSet 是否是首次设置
   * @param {number} 0:默认值代表来自从(1):首次设置的(2):从updateConfig设置的;1:代表已经注入了js页面再设置启动
   **/
  globalSet.prototype.setConfig = function (data,isFirstSet=true,from=0) {
      /*多配置时,前置配置存储浏览器配置,后置配置存储手机端配置*/
      /*兼容pc端两次调用BonreeStart*/
      if(GS.sett.appId!==""&&isDefined(data.appId)&&from!==0){
          return
      }
      if(isFirstSet&&isDefined(data.osType)){
          this.secondSett=extend(this.secondSett,data);
              return
      }
      /*sdk初始化页面已经嵌入js*/
      if(!isFirstSet&&from===1){
          if(isDefined(data.osType)){
              this.secondSett=extend(this.secondSett,data);
              return
          }else {
              extend(this.sett,data);
              return
          }   
      }
      /*第一次初始化/重新更新appid接口会走下面只更新主配置*/
      if (isDefined(data.probability)) { // 判断启动不启动
          if (typeof data.probability === "number") {
              this.checkProbability(data.probability);
          } else {
              log("C100");
          }
      }
      if (this.sett.probability) { // 探针启动
          extend(this.sett,data);
          if(this.sett.appId&&isFirstSet===true){
              sessionM.newAppid(this.sett.appId); 
          }
          if(this.sett.userId){
              if(isDefined(this.sett.extraInfo)){
                  setUserID(this.sett.userId);
                  setExtraInfo(this.sett.extraInfo);
              }else {
                  setUserID(this.sett.userId);
              }
              // 新增userId的逻辑
              getUserIdManageClass.changeUseAPI(true);
          }
          // 新用户id逻辑
          if(isDefined(this.sett.userdefine)){
              getUserIdManageClass.checkOriginManageData(this.sett.userdefine);
          }
          if(this.sett.isDebuge&&isDefined(window.BonreeAgent)){
              window.BonreeAgent.isDebuge=true;
          }
          if(this.sett.isDebuge&&isDefined(window.BonreeClient)){
              window.BonreeClient.isDebuge=true;
          }
      }
  };

  globalSet.prototype.checkProbability = function (pro) {
      let ran = Math.random() * GC.THOUSAND <= pro;
      if (ran) {
          this.sett.probability = GC.THOUSAND;
      } else {
          this.sett.probability = GC.ZERO;
      }
  };
  globalSet.prototype.setData=function(key,val){
      if(isDefined(key)&&isDefined(val)){
          this.sett[key]=val;
      }else {
          return false
      }
  };

  var GS = new globalSet();
  /**
   * @descripe 判断是否是IOS平台
   **/
  function isIOS(osType){
      return osType===GC.IOS
    }
  /**
   * @descripe 判断是否是hos平台
   **/
  function isHOS(osType){
      return osType===GC.HOS
      }
  /**
   * @descripe 判断是否是broswer平台
   **/
  function isBrowser(type) {
      return type === GC.BROWSER;
  }


  // 原 urlChange：这里通过代码兼容的方式来去掉这个字段

  /* 
  * probability: 原有逻辑-默认值-重新计算配置值，返回true或者false，这里做简化处理，在原有值上赋值为0和1，出于性能考量，
  * 重新赋值的程序执行前需要校验配置参数里是否有对应的参数否则不执行重新赋值的逻辑
  */

  // 原enable：控制探针是是否开启，这里去掉

  // pageready=>1;pageload=>2
  class global {
      constructor(){
          this.state=0;
          this.userInfoMap={};
          this.user=undefined;
          this.firstUserInfoSetMapKey='';
          this.lastUserInfoSetMapKey='';
          this.setUserInfoTimeStamp=0;
          this.title="noTitle";
          this.BonreeRecordState=false;
      }

      setData(key,val){
          if(isDefined(key)&&isDefined(val)){
              this[key]=val;
          }else {
              return false
          }
      }
      changeState(i){
          this.state=i;
      }
      getUserInfo(){
          if (isEmpty(this.userInfoMap)) {
              const userId = this.getUser();
              if (userId !== '') {
                  this.configUser(userId);
              }
          }
          return this.userInfoMap;
      }
      getUser(){
          if (isDefined(this.user)) {
              return user
          }
      
          var localUser = this.getLocalUser();
          if (isReadable(localUser)) {
              return localUser
          }
          return ''
      }
      getLocalUser(){
          if (isDefined(this.user)) {
              return this.user
          }
          var userKey = GS.sett.userKey;
          var localUser;
          if (isDefined(window.sessionStorage)) {
              localUser = sessionStorage.getItem(userKey);
              if (isReadable(localUser)) {
                  return localUser
              }
          }
          if (isDefined(window.localStorage)) {
              localUser = localStorage.getItem(userKey);
              if (isReadable(localUser)) {
                  return localUser
              }
          }
          return getCookie(userKey)
      }
      updateFirstUserInfoSetMapKey(value){
          this.firstUserInfoSetMapKey = value;
      }
      configUser(auser,isUserIDChange=false) {
          if (!isDefined(auser)) {
              log('C141');
              return;
          }
          if(auser instanceof Object){
              log('C142');
              return 
          }
          if(!isString(auser)){
              auser=""+auser;
          }
          if(!/^[\u4E00-\u9FFFa-zA-Z0-9:_\-@.\s/]+$/.test(auser)||auser.length>256){
              log("C143");
              return
          }
      
          if(!isUserIDChange){
              getUserIdManageClass.changeUseAPI(true);
          }
      
          let userExit = false;
          const key = hex_md5(auser);
          //判断用户信息是否已记录
          if (isDefined(this.userInfoMap[key])) {
              userExit = true;
          }
          //用户信息已经存在，更新用户的附加属性值
          if (userExit) {
              return 
          } else {
              if(isEmpty(this.userInfoMap)){
                  this.updateFirstUserInfoSetMapKey(key);
              }
              this.lastUserInfoSetMapKey = key;
              this.setUserInfoTimeStamp = now();
              let userInfo = {};
              userInfo.ui = auser;
              this.userInfoMap[key] = userInfo;
          }
      }
      configUserExtraInfo(extInfo){
          try{
              switch (typeof extInfo){
                  case "string":
                      if(extInfo.length>7000){return}
                      extInfo=JSON.parse(extInfo);
                      if(Object.getOwnPropertyNames(extInfo).length>64){
                          var handledExtInfo={};
                          Object.getOwnPropertyNames(extInfo).slice(0,64).forEach(function(val){
                              handledExtInfo[val]=extInfo[val];
                          });
                          extInfo=handledExtInfo;
                      }
                      break;
                  case "object":
                      if(JSON.stringify(extInfo).length>7000){return }
                      if(Object.getOwnPropertyNames(extInfo).length>64){
                          var handledExtInfo={}; 
                          Object.getOwnPropertyNames(extInfo).slice(0,64).forEach(function(val){
                              handledExtInfo[val]=extInfo[val];
                          });
                          extInfo=handledExtInfo;
                      }
                      break;
                  default:
                      return
              }
             
              
          }catch(e){

          }
          if(!isDefined(extInfo)){
              return 
          }
          if(isEmpty(this.userInfoMap)){
              return 
          }
          this.userInfoMap[this.lastUserInfoSetMapKey]['ei']=JSON.stringify(extInfo);
      }
  }
  class usdManage{
      constructor(){
          this.usdTime=0;
      }
      initUsdTime(){
          this.usdTime=0;
      }
      changUsdTime(data){
          if(isDefined(data)){
              this.usdTime=data;
          }
      }
  }



  function setUserID(auser,isUserIDChange=false) {
     globalData.configUser(auser,isUserIDChange);
  }
  function setExtraInfo(extraInfo) {
      globalData.configUserExtraInfo(extraInfo);
  }

  let globalData=new global();
  let usdManager=new usdManage();

  var LIBVERSION = '0.7.28',
      EMPTY = '',
      UNKNOWN = '?',
      FUNC_TYPE = 'function',
      UNDEF_TYPE = 'undefined',
      OBJ_TYPE = 'object',
      STR_TYPE = 'string',
      MAJOR = 'major', 
      MODEL = 'model',
      NAME$1 = 'name',
      TYPE$2 = 'type',
      VENDOR = 'vendor',
      VERSION = 'version',
      ARCHITECTURE = 'architecture',
      CONSOLE = 'console',
      MOBILE = 'mobile',
      TABLET = 'tablet',
      SMARTTV = 'smarttv',
      WEARABLE = 'wearable',
      EMBEDDED = 'embedded',
      UA_MAX_LENGTH = 255;
  ///////////
  // Helper
  //////////
  var util = {
      extend: function (regexes, extensions) {
          var mergedRegexes = {};
          for (var i in regexes) {
              if (extensions[i] && extensions[i].length % 2 === 0) {
                  mergedRegexes[i] = extensions[i].concat(regexes[i]);
              } else {
                  mergedRegexes[i] = regexes[i];
              }
          }
          return mergedRegexes;
      },
      has: function (str1, str2) {
          return typeof str1 === STR_TYPE ? str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1 : false;
      },
      lowerize: function (str) {
          return str.toLowerCase();
      },
      major: function (version) {
          return typeof (version) === STR_TYPE ? version.replace(/[^\d\.]/g, '').split(".")[0] : undefined;
      },
      trim: function (str, len) {
          str = str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
          return typeof (len) === UNDEF_TYPE ? str : str.substring(0, UA_MAX_LENGTH);
      }
  };
  ///////////////
  // Map helper
  //////////////
  var mapper = {

      rgx: function (ua, arrays) {

          var i = 0, j, k, p, q, matches, match;

          // loop through all regexes maps
          while (i < arrays.length && !matches) {

              var regex = arrays[i],       // even sequence (0,2,4,..)
                  props = arrays[i + 1];   // odd sequence (1,3,5,..)
              j = k = 0;

              // try matching uastring with regexes
              while (j < regex.length && !matches) {

                  matches = regex[j++].exec(ua);

                  if (!!matches) {
                      for (p = 0; p < props.length; p++) {
                          match = matches[++k];
                          q = props[p];
                          // check if given property is actually array
                          if (typeof q === OBJ_TYPE && q.length > 0) {
                              if (q.length == 2) {
                                  if (typeof q[1] == FUNC_TYPE) {
                                      // assign modified match
                                      this[q[0]] = q[1].call(this, match);
                                  } else {
                                      // assign given value, ignore regex match
                                      this[q[0]] = q[1];
                                  }
                              } else if (q.length == 3) {
                                  // check whether function or regex
                                  if (typeof q[1] === FUNC_TYPE && !(q[1].exec && q[1].test)) {
                                      // call function (usually string mapper)
                                      this[q[0]] = match ? q[1].call(this, match, q[2]) : undefined;
                                  } else {
                                      // sanitize match using given regex
                                      this[q[0]] = match ? match.replace(q[1], q[2]) : undefined;
                                  }
                              } else if (q.length == 4) {
                                  this[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined;
                              }
                          } else {
                              this[q] = match ? match : undefined;
                          }
                      }
                  }
              }
              i += 2;
          }
      },

      str: function (str, map) {

          for (var i in map) {
              // check if array
              if (typeof map[i] === OBJ_TYPE && map[i].length > 0) {
                  for (var j = 0; j < map[i].length; j++) {
                      if (util.has(map[i][j], str)) {
                          return (i === UNKNOWN) ? undefined : i;
                      }
                  }
              } else if (util.has(map[i], str)) {
                  return (i === UNKNOWN) ? undefined : i;
              }
          }
          return str;
      }
  };
  ///////////////
  // String map
  //////////////
  var maps = {
      browser: {
          // Safari < 3.0
          oldSafari: {
              version: {
                  '1.0': '/8',
                  '1.2': '/1',
                  '1.3': '/3',
                  '2.0': '/412',
                  '2.0.2': '/416',
                  '2.0.3': '/417',
                  '2.0.4': '/419',
                  '?': '/'
              }
          },
          oldEdge: {
              version: {
                  '0.1': '12.',
                  '21': '13.',
                  '31': '14.',
                  '39': '15.',
                  '41': '16.',
                  '42': '17.',
                  '44': '18.'
              }
          }
      },
      os: {
          windows: {
              version: {
                  'ME': '4.90',
                  'NT 3.11': 'NT3.51',
                  'NT 4.0': 'NT4.0',
                  '2000': 'NT 5.0',
                  'XP': ['NT 5.1', 'NT 5.2'],
                  'Vista': 'NT 6.0',
                  '7': 'NT 6.1',
                  '8': 'NT 6.2',
                  '8.1': 'NT 6.3',
                  '10': ['NT 6.4', 'NT 10.0'],
                  'RT': 'ARM'
              }
          }
      }
  };
  //////////////
  // Regex map
  /////////////
  var regexes = {

      browser: [[

          /\b(?:crmo|crios)\/([\w\.]+)/i                                      // Chrome for Android/iOS
      ], [VERSION, [NAME$1, 'Chrome']], [
          /edg(?:e|ios|a)?\/([\w\.]+)/i                                       // Microsoft Edge
      ], [VERSION, [NAME$1, 'Edge']], [
          // breaking change (reserved for next major release):
          ///edge\/([\w\.]+)/i                                                  // Old Edge (Trident)
          //], [[VERSION, mapper.str, maps.browser.oldEdge.version], [NAME, 'Edge']], [

          // Presto based
          /(opera\smini)\/([\w\.-]+)/i,                                       // Opera Mini
          /(opera\s[mobiletab]{3,6})\b.+version\/([\w\.-]+)/i,                // Opera Mobi/Tablet
          /(opera)(?:.+version\/|[\/\s]+)([\w\.]+)/i,                         // Opera
      ], [NAME$1, VERSION], [
          /opios[\/\s]+([\w\.]+)/i                                            // Opera mini on iphone >= 8.0
      ], [VERSION, [NAME$1, 'Opera Mini']], [
          /\sopr\/([\w\.]+)/i                                                 // Opera Webkit
      ], [VERSION, [NAME$1, 'Opera']], [

          // Mixed
          /(kindle)\/([\w\.]+)/i,                                             // Kindle
          /(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]*)/i,     // Lunascape/Maxthon/Netfront/Jasmine/Blazer
          // Trident based
          /(avant\s|iemobile|slim)(?:browser)?[\/\s]?([\w\.]*)/i,             // Avant/IEMobile/SlimBrowser
          /(ba?idubrowser)[\/\s]?([\w\.]+)/i,                                 // Baidu Browser
          /(?:ms|\()(ie)\s([\w\.]+)/i,                                        // Internet Explorer

          // Webkit/KHTML based
          /(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon)\/([\w\.-]+)/i,
          // Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron/Iridium/PhantomJS/Bowser/QupZilla/Falkon
          /(rekonq|puffin|brave|whale|qqbrowserlite|qq)\/([\w\.]+)/i,         // Rekonq/Puffin/Brave/Whale/QQBrowserLite/QQ, aka ShouQ
          /(weibo)__([\d\.]+)/i                                               // Weibo
      ], [NAME$1, VERSION], [
          /(?:[\s\/]uc?\s?browser|(?:juc.+)ucweb)[\/\s]?([\w\.]+)/i           // UCBrowser
      ], [VERSION, [NAME$1, 'UCBrowser']], [
          /(?:windowswechat)?\sqbcore\/([\w\.]+)\b.*(?:windowswechat)?/i      // WeChat Desktop for Windows Built-in Browser
      ], [VERSION, [NAME$1, 'WeChat(Win) Desktop']], [
          /micromessenger\/([\w\.]+)/i                                        // WeChat
      ], [VERSION, [NAME$1, 'WeChat']], [
          /konqueror\/([\w\.]+)/i                                             // Konqueror
      ], [VERSION, [NAME$1, 'Konqueror']], [
          /trident.+rv[:\s]([\w\.]{1,9})\b.+like\sgecko/i                     // IE11
      ], [VERSION, [NAME$1, 'IE']], [
          /yabrowser\/([\w\.]+)/i                                             // Yandex
      ], [VERSION, [NAME$1, 'Yandex']], [
          /(avast|avg)\/([\w\.]+)/i                                           // Avast/AVG Secure Browser
      ], [[NAME$1, /(.+)/, '$1 Secure Browser'], VERSION], [
          /focus\/([\w\.]+)/i                                                 // Firefox Focus
      ], [VERSION, [NAME$1, 'Firefox Focus']], [
          /opt\/([\w\.]+)/i                                                   // Opera Touch
      ], [VERSION, [NAME$1, 'Opera Touch']], [
          /coc_coc_browser\/([\w\.]+)/i                                       // Coc Coc Browser
      ], [VERSION, [NAME$1, 'Coc Coc']], [
          /dolfin\/([\w\.]+)/i                                                // Dolphin
      ], [VERSION, [NAME$1, 'Dolphin']], [
          /coast\/([\w\.]+)/i                                                 // Opera Coast
      ], [VERSION, [NAME$1, 'Opera Coast']],
      [/xiaomi\/miuibrowser\/([\w\.]+)/i                                  // MIUI Browser
      ], [VERSION, [NAME$1, 'MIUI Browser']], [
          /fxios\/([\w\.-]+)/i                                                // Firefox for iOS
      ], [VERSION, [NAME$1, 'Firefox']], [
          /(qihu|qhbrowser|qihoobrowser|360browser)/i                         // 360
      ], [[NAME$1, '360 Browser']], [
          /(oculus|samsung|sailfish)browser\/([\w\.]+)/i
      ], [[NAME$1, /(.+)/, '$1 Browser'], VERSION], [                       // Oculus/Samsung/Sailfish Browser
          /(comodo_dragon)\/([\w\.]+)/i                                       // Comodo Dragon
      ], [[NAME$1, /_/g, ' '], VERSION], [
          /\s(electron)\/([\w\.]+)\ssafari/i,                                 // Electron-based App
          /(tesla)(?:\sqtcarbrowser|\/(20[12]\d\.[\w\.-]+))/i,                // Tesla
          /m?(qqbrowser|baiduboxapp|2345Explorer)[\/\s]?([\w\.]+)/i           // QQBrowser/Baidu App/2345 Browser
      ], [NAME$1, VERSION], [
          /(MetaSr)[\/\s]?([\w\.]+)/i,                                        // SouGouBrowser
          /(LBBROWSER)/i                                                      // LieBao Browser
      ], [NAME$1], [

          // WebView
          /;fbav\/([\w\.]+);/i                                                // Facebook App for iOS & Android with version
      ], [VERSION, [NAME$1, 'Facebook']], [
          /FBAN\/FBIOS|FB_IAB\/FB4A/i                                         // Facebook App for iOS & Android without version
      ], [[NAME$1, 'Facebook']], [
          /safari\s(line)\/([\w\.]+)/i,                                       // Line App for iOS
          /\b(line)\/([\w\.]+)\/iab/i,                                        // Line App for Android
          /(chromium|instagram)[\/\s]([\w\.-]+)/i                             // Chromium/Instagram
      ], [NAME$1, VERSION], [
          /\bgsa\/([\w\.]+)\s.*safari\//i                                     // Google Search Appliance on iOS
      ], [VERSION, [NAME$1, 'GSA']], [

          /headlesschrome(?:\/([\w\.]+)|\s)/i                                 // Chrome Headless
      ], [VERSION, [NAME$1, 'Chrome Headless']], [

          /\swv\).+(chrome)\/([\w\.]+)/i                                      // Chrome WebView
      ], [[NAME$1, 'Chrome WebView'], VERSION], [

          /droid.+\sversion\/([\w\.]+)\b.+(?:mobile\ssafari|safari)/i         // Android Browser
      ], [VERSION, [NAME$1, 'Android Browser']], [

          /(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i      // Chrome/OmniWeb/Arora/Tizen/Nokia
      ], [NAME$1, VERSION], [

          /version\/([\w\.]+)\s.*mobile\/\w+\s(safari)/i                      // Mobile Safari
      ], [VERSION, [NAME$1, 'Mobile Safari']], [
          /version\/([\w\.]+)\s.*(mobile\s?safari|safari)/i                   // Safari & Safari Mobile
      ], [VERSION, NAME$1], [
          /webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i                     // Safari < 3.0
      ], [NAME$1, [VERSION, mapper.str, maps.browser.oldSafari.version]], [

          /(webkit|khtml)\/([\w\.]+)/i
      ], [NAME$1, VERSION], [

          // Gecko based
          /(navigator|netscape)\/([\w\.-]+)/i                                 // Netscape
      ], [[NAME$1, 'Netscape'], VERSION], [
          /ile\svr;\srv:([\w\.]+)\).+firefox/i                                // Firefox Reality
      ], [VERSION, [NAME$1, 'Firefox Reality']], [
          /ekiohf.+(flow)\/([\w\.]+)/i,                                       // Flow
          /(swiftfox)/i,                                                      // Swiftfox
          /(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i,
          // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror
          /(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([\w\.-]+)$/i,
          // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix
          /(firefox)\/([\w\.]+)\s[\w\s\-]+\/[\w\.]+$/i,                       // Other Firefox-based
          /(mozilla)\/([\w\.]+)\s.+rv\:.+gecko\/\d+/i,                        // Mozilla

          // Other
          /(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir)[\/\s]?([\w\.]+)/i,
          // Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/Sleipnir
          /(links)\s\(([\w\.]+)/i,                                            // Links
          /(gobrowser)\/?([\w\.]*)/i,                                         // GoBrowser
          /(ice\s?browser)\/v?([\w\._]+)/i,                                   // ICE Browser
          /(mosaic)[\/\s]([\w\.]+)/i                                          // Mosaic
      ], [NAME$1, VERSION]
      ],

      cpu: [[

          /(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i                     // AMD64 (x64)
      ], [[ARCHITECTURE, 'amd64']], [

          /(ia32(?=;))/i                                                      // IA32 (quicktime)
      ], [[ARCHITECTURE, util.lowerize]], [

          /((?:i[346]|x)86)[;\)]/i                                            // IA32 (x86)
      ], [[ARCHITECTURE, 'ia32']], [

          /\b(aarch64|armv?8e?l?)\b/i                                         // ARM64
      ], [[ARCHITECTURE, 'arm64']], [

          /\b(arm(?:v[67])?ht?n?[fl]p?)\b/i                                   // ARMHF
      ], [[ARCHITECTURE, 'armhf']], [

          // PocketPC mistakenly identified as PowerPC
          /windows\s(ce|mobile);\sppc;/i
      ], [[ARCHITECTURE, 'arm']], [

          /((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i                           // PowerPC
      ], [[ARCHITECTURE, /ower/, '', util.lowerize]], [

          /(sun4\w)[;\)]/i                                                    // SPARC
      ], [[ARCHITECTURE, 'sparc']], [

          /((?:avr32|ia64(?=;))|68k(?=\))|\barm(?:64|(?=v(?:[1-7]|[5-7]1)l?|;|eabi))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i
          // IA64, 68K, ARM/64, AVR/32, IRIX/64, MIPS/64, SPARC/64, PA-RISC
      ], [[ARCHITECTURE, util.lowerize]]
      ],

      device: [[

          //////////////////////////
          // MOBILES & TABLETS
          // Ordered by popularity
          /////////////////////////

          // Samsung
          /\b(sch-i[89]0\d|shw-m380s|sm-[pt]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus\s10)/i
      ], [MODEL, [VENDOR, 'Samsung'], [TYPE$2, TABLET]], [
          /\b((?:s[cgp]h|gt|sm)-\w+|galaxy\snexus)/i,
          /\ssamsung[\s-]([\w-]+)/i,
          /sec-(sgh\w+)/i
      ], [MODEL, [VENDOR, 'Samsung'], [TYPE$2, MOBILE]], [

          // Apple
          /\((ip(?:hone|od)[\s\w]*);/i                                        // iPod/iPhone
      ], [MODEL, [VENDOR, 'Apple'], [TYPE$2, MOBILE]], [
          /\((ipad);[\w\s\),;-]+apple/i,                                      // iPad
          /applecoremedia\/[\w\.]+\s\((ipad)/i,
          /\b(ipad)\d\d?,\d\d?[;\]].+ios/i
      ], [MODEL, [VENDOR, 'Apple'], [TYPE$2, TABLET]], [

          // Huawei
          /\b((?:agr|ags[23]|bah2?|sht?)-a?[lw]\d{2})/i,
      ], [MODEL, [VENDOR, 'Huawei'], [TYPE$2, TABLET]], [
          /d\/huawei([\w\s-]+)[;\)]/i,
          /\b(nexus\s6p|vog-[at]?l\d\d|ane-[at]?l[x\d]\d|eml-a?l\d\da?|lya-[at]?l\d[\dc]|clt-a?l\d\di?|ele-l\d\d)/i,
          /\b(\w{2,4}-[atu][ln][01259][019])[;\)\s]/i
      ], [MODEL, [VENDOR, 'Huawei'], [TYPE$2, MOBILE]], [

          // Xiaomi
          /\b(poco[\s\w]+)(?:\sbuild|\))/i,                                   // Xiaomi POCO
          /\b;\s(\w+)\sbuild\/hm\1/i,                                         // Xiaomi Hongmi 'numeric' models
          /\b(hm[\s\-_]?note?[\s_]?(?:\d\w)?)\sbuild/i,                       // Xiaomi Hongmi
          /\b(redmi[\s\-_]?(?:note|k)?[\w\s_]+)(?:\sbuild|\))/i,              // Xiaomi Redmi
          /\b(mi[\s\-_]?(?:a\d|one|one[\s_]plus|note lte)?[\s_]?(?:\d?\w?)[\s_]?(?:plus)?)\sbuild/i  // Xiaomi Mi
      ], [[MODEL, /_/g, ' '], [VENDOR, 'Xiaomi'], [TYPE$2, MOBILE]], [
          /\b(mi[\s\-_]?(?:pad)(?:[\w\s_]+))(?:\sbuild|\))/i                  // Mi Pad tablets
      ], [[MODEL, /_/g, ' '], [VENDOR, 'Xiaomi'], [TYPE$2, TABLET]], [

          // OPPO
          /;\s(\w+)\sbuild.+\soppo/i,
          /\s(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007)\b/i
      ], [MODEL, [VENDOR, 'OPPO'], [TYPE$2, MOBILE]], [

          // Vivo
          /\svivo\s(\w+)(?:\sbuild|\))/i,
          /\s(v[12]\d{3}\w?[at])(?:\sbuild|;)/i
      ], [MODEL, [VENDOR, 'Vivo'], [TYPE$2, MOBILE]], [

          // Realme
          /\s(rmx[12]\d{3})(?:\sbuild|;)/i
      ], [MODEL, [VENDOR, 'Realme'], [TYPE$2, MOBILE]], [

          // Motorola
          /\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?:?(\s4g)?)\b[\w\s]+build\//i,
          /\smot(?:orola)?[\s-](\w*)/i,
          /((?:moto[\s\w\(\)]+|xt\d{3,4}|nexus\s6)(?=\sbuild|\)))/i
      ], [MODEL, [VENDOR, 'Motorola'], [TYPE$2, MOBILE]], [
          /\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i
      ], [MODEL, [VENDOR, 'Motorola'], [TYPE$2, TABLET]], [

          // LG
          /((?=lg)?[vl]k\-?\d{3})\sbuild|\s3\.[\s\w;-]{10}lg?-([06cv9]{3,4})/i
      ], [MODEL, [VENDOR, 'LG'], [TYPE$2, TABLET]], [
          /(lm-?f100[nv]?|nexus\s[45])/i,
          /lg[e;\s\/-]+((?!browser|netcast)\w+)/i,
          /\blg(\-?[\d\w]+)\sbuild/i
      ], [MODEL, [VENDOR, 'LG'], [TYPE$2, MOBILE]], [

          // Lenovo
          /(ideatab[\w\-\s]+)/i,
          /lenovo\s?(s(?:5000|6000)(?:[\w-]+)|tab(?:[\s\w]+)|yt[\d\w-]{6}|tb[\d\w-]{6})/i        // Lenovo tablets
      ], [MODEL, [VENDOR, 'Lenovo'], [TYPE$2, TABLET]], [

          // Nokia
          /(?:maemo|nokia).*(n900|lumia\s\d+)/i,
          /nokia[\s_-]?([\w\.-]*)/i
      ], [[MODEL, /_/g, ' '], [VENDOR, 'Nokia'], [TYPE$2, MOBILE]], [

          // Google
          /droid.+;\s(pixel\sc)[\s)]/i                                        // Google Pixel C
      ], [MODEL, [VENDOR, 'Google'], [TYPE$2, TABLET]], [
          /droid.+;\s(pixel[\s\daxl]{0,6})(?:\sbuild|\))/i                    // Google Pixel
      ], [MODEL, [VENDOR, 'Google'], [TYPE$2, MOBILE]], [

          // Sony
          /droid.+\s([c-g]\d{4}|so[-l]\w+|xq-a\w[4-7][12])(?=\sbuild\/|\).+chrome\/(?![1-6]{0,1}\d\.))/i
      ], [MODEL, [VENDOR, 'Sony'], [TYPE$2, MOBILE]], [
          /sony\stablet\s[ps]\sbuild\//i,
          /(?:sony)?sgp\w+(?:\sbuild\/|\))/i
      ], [[MODEL, 'Xperia Tablet'], [VENDOR, 'Sony'], [TYPE$2, TABLET]], [

          // OnePlus
          /\s(kb2005|in20[12]5|be20[12][59])\b/i,
          /\ba000(1)\sbuild/i,                                                // OnePlus
          /\boneplus\s(a\d{4})[\s)]/i
      ], [MODEL, [VENDOR, 'OnePlus'], [TYPE$2, MOBILE]], [

          // Amazon
          /(alexa)webm/i,
          /(kf[a-z]{2}wi)(\sbuild\/|\))/i,                                    // Kindle Fire without Silk
          /(kf[a-z]+)(\sbuild\/|\)).+silk\//i                                 // Kindle Fire HD
      ], [MODEL, [VENDOR, 'Amazon'], [TYPE$2, TABLET]], [
          /(sd|kf)[0349hijorstuw]+(\sbuild\/|\)).+silk\//i                    // Fire Phone
      ], [[MODEL, 'Fire Phone'], [VENDOR, 'Amazon'], [TYPE$2, MOBILE]], [

          // BlackBerry
          /\((playbook);[\w\s\),;-]+(rim)/i                                   // BlackBerry PlayBook
      ], [MODEL, VENDOR, [TYPE$2, TABLET]], [
          /((?:bb[a-f]|st[hv])100-\d)/i,
          /\(bb10;\s(\w+)/i                                                   // BlackBerry 10
      ], [MODEL, [VENDOR, 'BlackBerry'], [TYPE$2, MOBILE]], [

          // Asus
          /(?:\b|asus_)(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus\s7|padfone|p00[cj])/i
      ], [MODEL, [VENDOR, 'ASUS'], [TYPE$2, TABLET]], [
          /\s(z[es]6[027][01][km][ls]|zenfone\s\d\w?)\b/i
      ], [MODEL, [VENDOR, 'ASUS'], [TYPE$2, MOBILE]], [

          // HTC
          /(nexus\s9)/i                                                       // HTC Nexus 9
      ], [MODEL, [VENDOR, 'HTC'], [TYPE$2, TABLET]], [
          /(htc)[;_\s-]{1,2}([\w\s]+(?=\)|\sbuild)|\w+)/i,                    // HTC

          // ZTE
          /(zte)-(\w*)/i,
          /(alcatel|geeksphone|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]*)/i // Alcatel/GeeksPhone/Nexian/Panasonic/Sony
      ], [VENDOR, [MODEL, /_/g, ' '], [TYPE$2, MOBILE]], [

          // Acer
          /droid[x\d\.\s;]+\s([ab][1-7]\-?[0178a]\d\d?)/i
      ], [MODEL, [VENDOR, 'Acer'], [TYPE$2, TABLET]], [

          // Meizu
          /droid.+;\s(m[1-5]\snote)\sbuild/i,
          /\bmz-([\w-]{2,})/i
      ], [MODEL, [VENDOR, 'Meizu'], [TYPE$2, MOBILE]], [

          // MIXED
          /(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[\s_-]?([\w-]*)/i,
          // BlackBerry/BenQ/Palm/Sony-Ericsson/Acer/Asus/Dell/Meizu/Motorola/Polytron
          /(hp)\s([\w\s]+\w)/i,                                               // HP iPAQ
          /(asus)-?(\w+)/i,                                                   // Asus
          /(microsoft);\s(lumia[\s\w]+)/i,                                    // Microsoft Lumia
          /(lenovo)[_\s-]?([\w-]+)/i,                                         // Lenovo
          /linux;.+(jolla);/i,                                                // Jolla
          /droid.+;\s(oppo)\s?([\w\s]+)\sbuild/i                              // OPPO
      ], [VENDOR, MODEL, [TYPE$2, MOBILE]], [

          /(archos)\s(gamepad2?)/i,                                           // Archos
          /(hp).+(touchpad(?!.+tablet)|tablet)/i,                             // HP TouchPad
          /(kindle)\/([\w\.]+)/i,                                             // Kindle
          /\s(nook)[\w\s]+build\/(\w+)/i,                                     // Nook
          /(dell)\s(strea[kpr\s\d]*[\dko])/i,                                 // Dell Streak
          /[;\/]\s?(le[\s\-]+pan)[\s\-]+(\w{1,9})\sbuild/i,                   // Le Pan Tablets
          /[;\/]\s?(trinity)[\-\s]*(t\d{3})\sbuild/i,                         // Trinity Tablets
          /\b(gigaset)[\s\-]+(q\w{1,9})\sbuild/i,                             // Gigaset Tablets
          /\b(vodafone)\s([\w\s]+)(?:\)|\sbuild)/i                            // Vodafone
      ], [VENDOR, MODEL, [TYPE$2, TABLET]], [

          /\s(surface\sduo)\s/i                                               // Surface Duo
      ], [MODEL, [VENDOR, 'Microsoft'], [TYPE$2, TABLET]], [
          /droid\s[\d\.]+;\s(fp\du?)\sbuild/i
      ], [MODEL, [VENDOR, 'Fairphone'], [TYPE$2, MOBILE]], [
          /\s(u304aa)\sbuild/i                                                // AT&T
      ], [MODEL, [VENDOR, 'AT&T'], [TYPE$2, MOBILE]], [
          /sie-(\w*)/i                                                        // Siemens
      ], [MODEL, [VENDOR, 'Siemens'], [TYPE$2, MOBILE]], [
          /[;\/]\s?(rct\w+)\sbuild/i                                          // RCA Tablets
      ], [MODEL, [VENDOR, 'RCA'], [TYPE$2, TABLET]], [
          /[;\/\s](venue[\d\s]{2,7})\sbuild/i                                 // Dell Venue Tablets
      ], [MODEL, [VENDOR, 'Dell'], [TYPE$2, TABLET]], [
          /[;\/]\s?(q(?:mv|ta)\w+)\sbuild/i                                   // Verizon Tablet
      ], [MODEL, [VENDOR, 'Verizon'], [TYPE$2, TABLET]], [
          /[;\/]\s(?:barnes[&\s]+noble\s|bn[rt])([\w\s\+]*)\sbuild/i          // Barnes & Noble Tablet
      ], [MODEL, [VENDOR, 'Barnes & Noble'], [TYPE$2, TABLET]], [
          /[;\/]\s(tm\d{3}\w+)\sbuild/i
      ], [MODEL, [VENDOR, 'NuVision'], [TYPE$2, TABLET]], [
          /;\s(k88)\sbuild/i                                                  // ZTE K Series Tablet
      ], [MODEL, [VENDOR, 'ZTE'], [TYPE$2, TABLET]], [
          /;\s(nx\d{3}j)\sbuild/i                                             // ZTE Nubia
      ], [MODEL, [VENDOR, 'ZTE'], [TYPE$2, MOBILE]], [
          /[;\/]\s?(gen\d{3})\sbuild.*49h/i                                   // Swiss GEN Mobile
      ], [MODEL, [VENDOR, 'Swiss'], [TYPE$2, MOBILE]], [
          /[;\/]\s?(zur\d{3})\sbuild/i                                        // Swiss ZUR Tablet
      ], [MODEL, [VENDOR, 'Swiss'], [TYPE$2, TABLET]], [
          /[;\/]\s?((zeki)?tb.*\b)\sbuild/i                                   // Zeki Tablets
      ], [MODEL, [VENDOR, 'Zeki'], [TYPE$2, TABLET]], [
          /[;\/]\s([yr]\d{2})\sbuild/i,
          /[;\/]\s(dragon[\-\s]+touch\s|dt)(\w{5})\sbuild/i                   // Dragon Touch Tablet
      ], [[VENDOR, 'Dragon Touch'], MODEL, [TYPE$2, TABLET]], [
          /[;\/]\s?(ns-?\w{0,9})\sbuild/i                                     // Insignia Tablets
      ], [MODEL, [VENDOR, 'Insignia'], [TYPE$2, TABLET]], [
          /[;\/]\s?((nxa|Next)-?\w{0,9})\sbuild/i                             // NextBook Tablets
      ], [MODEL, [VENDOR, 'NextBook'], [TYPE$2, TABLET]], [
          /[;\/]\s?(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05]))\sbuild/i
      ], [[VENDOR, 'Voice'], MODEL, [TYPE$2, MOBILE]], [                    // Voice Xtreme Phones
          /[;\/]\s?(lvtel\-)?(v1[12])\sbuild/i                                // LvTel Phones
      ], [[VENDOR, 'LvTel'], MODEL, [TYPE$2, MOBILE]], [
          /;\s(ph-1)\s/i
      ], [MODEL, [VENDOR, 'Essential'], [TYPE$2, MOBILE]], [                // Essential PH-1
          /[;\/]\s?(v(100md|700na|7011|917g).*\b)\sbuild/i                    // Envizen Tablets
      ], [MODEL, [VENDOR, 'Envizen'], [TYPE$2, TABLET]], [
          /[;\/]\s?(trio[\s\w\-\.]+)\sbuild/i                                 // MachSpeed Tablets
      ], [MODEL, [VENDOR, 'MachSpeed'], [TYPE$2, TABLET]], [
          /[;\/]\s?tu_(1491)\sbuild/i                                         // Rotor Tablets
      ], [MODEL, [VENDOR, 'Rotor'], [TYPE$2, TABLET]], [
          /(shield[\w\s]+)\sbuild/i                                           // Nvidia Shield Tablets
      ], [MODEL, [VENDOR, 'Nvidia'], [TYPE$2, TABLET]], [
          /(sprint)\s(\w+)/i                                                  // Sprint Phones
      ], [VENDOR, MODEL, [TYPE$2, MOBILE]], [
          /(kin\.[onetw]{3})/i                                                // Microsoft Kin
      ], [[MODEL, /\./g, ' '], [VENDOR, 'Microsoft'], [TYPE$2, MOBILE]], [
          /droid\s[\d\.]+;\s(cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i     // Zebra
      ], [MODEL, [VENDOR, 'Zebra'], [TYPE$2, TABLET]], [
          /droid\s[\d\.]+;\s(ec30|ps20|tc[2-8]\d[kx])\)/i
      ], [MODEL, [VENDOR, 'Zebra'], [TYPE$2, MOBILE]], [

          ///////////////////
          // CONSOLES
          ///////////////////

          /\s(ouya)\s/i,                                                      // Ouya
          /(nintendo)\s([wids3utch]+)/i                                       // Nintendo
      ], [VENDOR, MODEL, [TYPE$2, CONSOLE]], [
          /droid.+;\s(shield)\sbuild/i                                        // Nvidia
      ], [MODEL, [VENDOR, 'Nvidia'], [TYPE$2, CONSOLE]], [
          /(playstation\s[345portablevi]+)/i                                  // Playstation
      ], [MODEL, [VENDOR, 'Sony'], [TYPE$2, CONSOLE]], [
          /[\s\(;](xbox(?:\sone)?(?!;\sxbox))[\s\);]/i                        // Microsoft Xbox
      ], [MODEL, [VENDOR, 'Microsoft'], [TYPE$2, CONSOLE]], [

          ///////////////////
          // SMARTTVS
          ///////////////////

          /smart-tv.+(samsung)/i                                              // Samsung
      ], [VENDOR, [TYPE$2, SMARTTV]], [
          /hbbtv.+maple;(\d+)/i
      ], [[MODEL, /^/, 'SmartTV'], [VENDOR, 'Samsung'], [TYPE$2, SMARTTV]], [
          /(?:linux;\snetcast.+smarttv|lg\snetcast\.tv-201\d)/i,              // LG SmartTV
      ], [[VENDOR, 'LG'], [TYPE$2, SMARTTV]], [
          /(apple)\s?tv/i                                                     // Apple TV
      ], [VENDOR, [MODEL, 'Apple TV'], [TYPE$2, SMARTTV]], [
          /crkey/i                                                            // Google Chromecast
      ], [[MODEL, 'Chromecast'], [VENDOR, 'Google'], [TYPE$2, SMARTTV]], [
          /droid.+aft([\w])(\sbuild\/|\))/i                                   // Fire TV
      ], [MODEL, [VENDOR, 'Amazon'], [TYPE$2, SMARTTV]], [
          /\(dtv[\);].+(aquos)/i                                              // Sharp
      ], [MODEL, [VENDOR, 'Sharp'], [TYPE$2, SMARTTV]], [
          /hbbtv\/\d+\.\d+\.\d+\s+\([\w\s]*;\s*(\w[^;]*);([^;]*)/i            // HbbTV devices
      ], [[VENDOR, util.trim], [MODEL, util.trim], [TYPE$2, SMARTTV]], [
          /[\s\/\(](android\s|smart[-\s]?|opera\s)tv[;\)\s]/i                 // SmartTV from Unidentified Vendors
      ], [[TYPE$2, SMARTTV]], [

          ///////////////////
          // WEARABLES
          ///////////////////

          /((pebble))app\/[\d\.]+\s/i                                         // Pebble
      ], [VENDOR, MODEL, [TYPE$2, WEARABLE]], [
          /droid.+;\s(glass)\s\d/i                                            // Google Glass
      ], [MODEL, [VENDOR, 'Google'], [TYPE$2, WEARABLE]], [
          /droid\s[\d\.]+;\s(wt63?0{2,3})\)/i
      ], [MODEL, [VENDOR, 'Zebra'], [TYPE$2, WEARABLE]], [

          ///////////////////
          // EMBEDDED
          ///////////////////

          /(tesla)(?:\sqtcarbrowser|\/20[12]\d\.[\w\.-]+)/i                   // Tesla
      ], [VENDOR, [TYPE$2, EMBEDDED]], [

          ////////////////////
          // MIXED (GENERIC)
          ///////////////////

          /droid .+?; ([^;]+?)(?: build|\) applewebkit).+? mobile safari/i    // Android Phones from Unidentified Vendors
      ], [MODEL, [TYPE$2, MOBILE]], [
          /droid .+?;\s([^;]+?)(?: build|\) applewebkit).+?(?! mobile) safari/i  // Android Tablets from Unidentified Vendors
      ], [MODEL, [TYPE$2, TABLET]], [
          /\s(tablet|tab)[;\/]/i,                                             // Unidentifiable Tablet
          /\s(mobile)(?:[;\/]|\ssafari)/i                                     // Unidentifiable Mobile
      ], [[TYPE$2, util.lowerize]], [
          /(android[\w\.\s\-]{0,9});.+build/i                                 // Generic Android Device
      ], [MODEL, [VENDOR, 'Generic']], [
          /(phone)/i
      ], [[TYPE$2, MOBILE]]
      ],

      engine: [[

          /windows.+\sedge\/([\w\.]+)/i                                       // EdgeHTML
      ], [VERSION, [NAME$1, 'EdgeHTML']], [

          /webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i                         // Blink
      ], [VERSION, [NAME$1, 'Blink']], [

          /(presto)\/([\w\.]+)/i,                                             // Presto
          /(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m/Goanna
          /ekioh(flow)\/([\w\.]+)/i,                                          // Flow
          /(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i,                          // KHTML/Tasman/Links
          /(icab)[\/\s]([23]\.[\d\.]+)/i                                      // iCab
      ], [NAME$1, VERSION], [

          /rv\:([\w\.]{1,9})\b.+(gecko)/i                                     // Gecko
      ], [VERSION, NAME$1]
      ],

      os: [[

          // Windows
          /microsoft\s(windows)\s(vista|xp)/i                                 // Windows (iTunes)
      ], [NAME$1, VERSION], [
          /(windows)\snt\s6\.2;\s(arm)/i,                                     // Windows RT
          /(windows\sphone(?:\sos)*)[\s\/]?([\d\.\s\w]*)/i,                   // Windows Phone
          /(windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)(?!.+xbox)/i
      ], [NAME$1, [VERSION, mapper.str, maps.os.windows.version]], [
          /(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i
      ], [[NAME$1, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [

          // iOS/macOS
          /ip[honead]{2,4}\b(?:.*os\s([\w]+)\slike\smac|;\sopera)/i,          // iOS
          /cfnetwork\/.+darwin/i
      ], [[VERSION, /_/g, '.'], [NAME$1, 'iOS']], [
          /(mac\sos\sx)\s?([\w\s\.]*)/i,
          /(macintosh|mac(?=_powerpc)\s)(?!.+haiku)/i                         // Mac OS
      ], [[NAME$1, 'Mac OS'], [VERSION, /_/g, '.']], [

          // Mobile OSes                                                      // Android/WebOS/Palm/QNX/Bada/RIM/MeeGo/Contiki/Sailfish OS
          /(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|sailfish|contiki)[\/\s-]?([\w\.]*)/i,
          /(blackberry)\w*\/([\w\.]*)/i,                                      // Blackberry
          /(tizen|kaios)[\/\s]([\w\.]+)/i,                                    // Tizen/KaiOS
          /\((series40);/i                                                    // Series 40
      ], [NAME$1, VERSION], [
          /\(bb(10);/i                                                        // BlackBerry 10
      ], [VERSION, [NAME$1, 'BlackBerry']], [
          /(?:symbian\s?os|symbos|s60(?=;)|series60)[\/\s-]?([\w\.]*)/i       // Symbian
      ], [VERSION, [NAME$1, 'Symbian']], [
          /mozilla.+\(mobile;.+gecko.+firefox/i                               // Firefox OS
      ], [[NAME$1, 'Firefox OS']], [
          /web0s;.+rt(tv)/i,
          /\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i                              // WebOS
      ], [VERSION, [NAME$1, 'webOS']], [

          // Google Chromecast
          /crkey\/([\d\.]+)/i                                                 // Google Chromecast
      ], [VERSION, [NAME$1, 'Chromecast']], [
          /(cros)\s[\w]+\s([\w\.]+\w)/i                                       // Chromium OS
      ], [[NAME$1, 'Chromium OS'], VERSION], [

          // Console
          /(nintendo|playstation)\s([wids345portablevuch]+)/i,                // Nintendo/Playstation
          /(xbox);\s+xbox\s([^\);]+)/i,                                       // Microsoft Xbox (360, One, X, S, Series X, Series S)

          // GNU/Linux based
          /(mint)[\/\s\(\)]?(\w*)/i,                                          // Mint
          /(mageia|vectorlinux)[;\s]/i,                                       // Mageia/VectorLinux
          /(joli|[kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?=\slinux)|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus|raspbian)(?:\sgnu\/linux)?(?:\slinux)?[\/\s-]?(?!chrom|package)([\w\.-]*)/i,
          // Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware
          // Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk/Linpus
          /(hurd|linux)\s?([\w\.]*)/i,                                        // Hurd/Linux
          /(gnu)\s?([\w\.]*)/i,                                               // GNU

          // BSD based
          /\s([frentopc-]{0,4}bsd|dragonfly)\s?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,  // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly
          /(haiku)\s(\w+)/i                                                   // Haiku
      ], [NAME$1, VERSION], [

          // Other
          /(sunos)\s?([\w\.\d]*)/i                                            // Solaris
      ], [[NAME$1, 'Solaris'], VERSION], [
          /((?:open)?solaris)[\/\s-]?([\w\.]*)/i,                             // Solaris
          /(aix)\s((\d)(?=\.|\)|\s)[\w\.])*/i,                                // AIX
          /(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms|fuchsia)/i,  // Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS/OpenVMS/Fuchsia
          /(unix)\s?([\w\.]*)/i                                               // UNIX
      ], [NAME$1, VERSION]
      ]
  };
  //全局缓存ua原始数据
  var _ua = ((typeof window !== 'undefined' && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY);
  class UAParser {
      constructor() {
          this.VERSION = LIBVERSION;
          this.BROWSER = {
              NAME: NAME$1,
              MAJOR: MAJOR, // deprecated
              VERSION: VERSION
          };
          this.CPU = {
              ARCHITECTURE: ARCHITECTURE
          };
          this.DEVICE = {
              MODEL: MODEL,
              VENDOR: VENDOR,
              TYPE: TYPE$2,
              CONSOLE: CONSOLE,
              MOBILE: MOBILE,
              SMARTTV: SMARTTV,
              TABLET: TABLET,
              WEARABLE: WEARABLE,
              EMBEDDED: EMBEDDED
          };
          this.ENGINE = {
              NAME: NAME$1,
              VERSION: VERSION
          };
          this.OS = {
              NAME: NAME$1,
              VERSION: VERSION
          };
      }
  }
  UAParser.prototype.getBrowser = function () {
      var _browser = { name: undefined, version: undefined };
      mapper.rgx.call(_browser, _ua, regexes.browser);
      _browser.major = util.major(_browser.version); // deprecated
      return _browser;
  };
  UAParser.prototype.getCPU = function () {
      var _cpu = { architecture: undefined };
      mapper.rgx.call(_cpu, _ua, regexes.cpu);
      return _cpu;
  };
  UAParser.prototype.getDevice = function () {
      var _device = { vendor: undefined, model: undefined, type: undefined };
      mapper.rgx.call(_device, _ua, regexes.device);
      return _device;
  };
  UAParser.prototype.getEngine = function () {
      var _engine = { name: undefined, version: undefined };
      mapper.rgx.call(_engine, _ua, regexes.engine);
      return _engine;
  };
  UAParser.prototype.getOS = function () {
      var _os = { name: undefined, version: undefined };
      mapper.rgx.call(_os, _ua, regexes.os);
      return _os;
  };
  UAParser.prototype.getUA = function () {
      return _ua;
  };
  UAParser.prototype.getResult = function () {
      return {
          ua: this.getUA(),
          browser: this.getBrowser(),
          engine: this.getEngine(),
          os: this.getOS(),
          device: this.getDevice(),
          cpu: this.getCPU()
      };
  };

  // import {load} from "./finger/index"

  var CLIENTID = 'br-client';
  //构建设备信息对象
  const deviceInfo = {};
  let uaInfo = {};
  // 设备指纹id
  // let pringID
  // 设备指纹id
    // document&&document.addEventListener('readystatechange', event => {
    //   if (event.target.readyState === 'complete') {
    //     if(checkBrowserIsOld()){
    //       try{
    //         // new Promise((resolve,reject)=>resolve(load())).then(fp => fp.get()).then(result =>{
    //           // pringID=result.visitorId;
    //           //provide to BrLog
    //           if(isDefined(window.bonreeRUM)){
    //             window.bonreeRUM['fingerId']=pringID
    //             setCookie(CLIENTID,pringID,{
    //               path: '/',
    //               expires: 'Thu, 01 Jan 2099 00:00:01 GMT;'
    //             })
    //           }
    //         // })
    //       }catch(error){
    //         console.log(error)
    //       }
    //   }
    //   }
    // });  


  /**
   * 构建设备的唯一ID
   * @returns 
   */
  const getClientID = function () {
    /* 为什么不使用localStorage？隐私模式下可能会有问题，未验证 */
    var defaultUser = getCookie(CLIENTID);
    if (!isReadable(defaultUser)) {
            defaultUser =uuid();
        setCookie(CLIENTID, defaultUser,{
          path: '/',
          expires: 'Thu, 01 Jan 2099 00:00:01 GMT;'
        });
    }
    return defaultUser
  };
  /**
   * 
   * @returns 
   */
  function parserUA() {
      if (!isEmpty(uaInfo)&&UAParser) {
          return;
      }
      try {
          //截取userAgent信息
          const uaParser = new UAParser();
          uaInfo =uaParser&& uaParser.getResult()||{};
      } catch (err) {
        log(err);
          //捕获异常不做处理
      }
  }

  function getOtName(name){
      // let useAgent=getUserAgent()
      if(name){
         if(/iphone|ipad|ios/i.test(name)){
          return 0
         }
         if(/android/i.test(name)){
          return 1
         }
         if(/windows/i.test(name)){
          return 2
         }
         if(/harmonyOS/i.test(name)){
          return 3
         }
         if(/mac/i.test(name)){
          return 4
         }
      return 1
  }
  }
  /**
   * 获取设备（浏览器）信息API
   * @returns 
   */
  function getDeviceInfo() {
    try {
      if(checkBrowserIsOld()){
        parserUA();
      }
      deviceInfo.di =getClientID();           //device id 设备ID [非空字段]
      deviceInfo.a = 'user';              //authority 权限 「root,user,system」[非空字段]
      deviceInfo.ot =  uaInfo&& isDefined(uaInfo.os) ? uaInfo.os.name&&getOtName(uaInfo.os.name) : '1';                  //type OS类型 「0:ios,1:android,2:windows,4:browser」
      deviceInfo.ram = isDefined(navigator.deviceMemory)&&navigator.deviceMemory * 1024||-1;     //total RAM 整机RAM内存
      deviceInfo.l = navigator.language ||navigator.userLanguage;  //language 语言 [非空字段]
      deviceInfo.ds = window.screen.width + '*' + window.screen.height;
      deviceInfo.rom=-1;
      // deviceInfo.ch="unknown";
      // deviceInfo.cm="unknown";
      deviceInfo.bn = uaInfo&& isDefined(uaInfo.os) ? uaInfo.os.name : 'unknown';  //os name 品牌信息 [非空字段]
      deviceInfo.omv = uaInfo&&uaInfo.os&&uaInfo.os.version ? uaInfo.os.version : 'unknown';      //os version OS主版本 [非空字段]  
      deviceInfo.ci = uaInfo && isDefined(uaInfo.cpu) ? (uaInfo.cpu.architecture&&uaInfo.cpu.architecture||"unknown") : 'unknown';  //CPU 架构
      deviceInfo.ctn= uaInfo&&isDefined(uaInfo.browser) ? uaInfo.browser.name : 'unknown'; // 浏览器名字
      deviceInfo.ctv=uaInfo&&uaInfo.browser&&uaInfo.browser.version ? uaInfo.browser.version : 'unknown'; //浏览器版本
      if(isDefined(uaInfo.device) && isDefined(uaInfo.device.model)){
          deviceInfo.m = uaInfo.device.model;    //model 型号
      }
      setDeviceForLog(deviceInfo.di);
    } catch (error) {
      log(error,true);
      return {}
    }
    return deviceInfo;
  }

  function checkBrowserIsOld(){
    try {
        var exBrowser=["Firefox/47"];
        let  userAgent=navigator.userAgent&&navigator.userAgent.match(/(firefox|msie|chrome|safari)[/\s]([\d.]+)/ig)||undefined;
        if(userAgent&&userAgent.length>0){
          let tag=userAgent[0].split("/");
          for(let i=0,j=exBrowser.length-1;i<=j;i++){
            let settag=exBrowser[i];
            settag=settag.split("/");
            if(settag[0]===tag[0]&&Number(tag[1].split(".")[0])<=Number(settag[1])){
              return false
            }
          }
        }
        return true
    } catch (error) {
      log(error);
    }
    return false
  }

  /******Sm4模块************/
  let Proxy$1 = class Proxy{
    zero(n) {
     var a;
     if (n > 0) {
      a = "0";
      for (var j = 1; j < n; j++) {
       a += a;
      }
      return a;
     }
     return '';
    }
    stringToArray(string) {
     // debugger;
     var arr = [];
     var length = string.length;
     for (var i = 0; i < length; i++) {
      var code = string.charCodeAt(i);
      if (19968 < code && code < 40869) {
       var bin = code.toString(2);
       var bin1 = '1110';
       var bin2 = '10';
       var bin3 = '10';
       var binlen = bin.length;
       if (binlen <= 6) {
        bin3 = bin3 + this.zero(6 - binlen) + bin;
        bin2 = bin2 + this.zero(6);
        bin1 = bin1 + this.zero(4);
       } else if (binlen > 6 && binlen <= 12) {
        bin3 = bin3 + bin.slice(-6);
        bin2 = bin2 + this.zero(12 - binlen) + bin.substr(0, binlen - 6);
        bin1 = bin1 + this.zero(4);
       } else {
        bin3 = bin3 + bin.slice(-6);
        bin2 = bin2 + bin.substr(binlen - 12, 6);
        bin1 = bin1 + this.zero(16 - binlen) + bin.substr(0, binlen - 12);
       }
       arr.push(parseInt(bin1, 2), parseInt(bin2, 2), parseInt(bin3, 2));
      } else {
       arr.push(code);
      }
     }
     return arr;
    }
    stringToArrayBufferInUtf8(str) {
     // if not browser env, then require node.js's util. otherwise just use window's
     // const TextEncoder = (typeof window === 'undefined') ? require('util').TextEncoder : window.TextEncoder
     // always utf-8
     return this.stringToArray(str);
    }
   };
   if (!Array.prototype.fill) {
    Object.defineProperty(Array.prototype, 'fill', {
     value: function value(_value) {
      // Steps 1-2.
      if (this == null) {
       throw new TypeError('this is null or not defined');
      }
   
      var O = Object(this); // Steps 3-5.
      var len = O.length >>> 0; // Steps 6-7.
      var start = arguments[1];
      var relativeStart = start >> 0; // Step 8.
      var k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); // Steps 9-10.
      var end = arguments[2];
      var relativeEnd = end === undefined ? len : end >> 0; // Step 11.
      var _final = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len); // Step 12.
      while (k < _final) {
       O[k] = _value;
       k++;
      } // Step 13.
   
      return O;
     }
    });
   }
   var UINT8_BLOCK = 16;
   var Sbox = new Uint8Array([0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05, 0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99, 0x9c, 0x42, 0x50, 0xf4, 0x91, 0xef, 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43, 0xed, 0xcf, 0xac, 0x62, 0xe4, 0xb3, 0x1c, 0xa9, 0xc9, 0x08, 0xe8, 0x95, 0x80, 0xdf, 0x94, 0xfa, 0x75, 0x8f, 0x3f, 0xa6, 0x47, 0x07, 0xa7, 0xfc, 0xf3, 0x73, 0x17, 0xba, 0x83, 0x59, 0x3c, 0x19, 0xe6, 0x85, 0x4f, 0xa8, 0x68, 0x6b, 0x81, 0xb2, 0x71, 0x64, 0xda, 0x8b, 0xf8, 0xeb, 0x0f, 0x4b, 0x70, 0x56, 0x9d, 0x35, 0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, 0xd1, 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, 0x87, 0xd4, 0x00, 0x46, 0x57, 0x9f, 0xd3, 0x27, 0x52, 0x4c, 0x36, 0x02, 0xe7, 0xa0, 0xc4, 0xc8, 0x9e, 0xea, 0xbf, 0x8a, 0xd2, 0x40, 0xc7, 0x38, 0xb5, 0xa3, 0xf7, 0xf2, 0xce, 0xf9, 0x61, 0x15, 0xa1, 0xe0, 0xae, 0x5d, 0xa4, 0x9b, 0x34, 0x1a, 0x55, 0xad, 0x93, 0x32, 0x30, 0xf5, 0x8c, 0xb1, 0xe3, 0x1d, 0xf6, 0xe2, 0x2e, 0x82, 0x66, 0xca, 0x60, 0xc0, 0x29, 0x23, 0xab, 0x0d, 0x53, 0x4e, 0x6f, 0xd5, 0xdb, 0x37, 0x45, 0xde, 0xfd, 0x8e, 0x2f, 0x03, 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b, 0x51, 0x8d, 0x1b, 0xaf, 0x92, 0xbb, 0xdd, 0xbc, 0x7f, 0x11, 0xd9, 0x5c, 0x41, 0x1f, 0x10, 0x5a, 0xd8, 0x0a, 0xc1, 0x31, 0x88, 0xa5, 0xcd, 0x7b, 0xbd, 0x2d, 0x74, 0xd0, 0x12, 0xb8, 0xe5, 0xb4, 0xb0, 0x89, 0x69, 0x97, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0xb9, 0xf1, 0x09, 0xc5, 0x6e, 0xc6, 0x84, 0x18, 0xf0, 0x7d, 0xec, 0x3a, 0xdc, 0x4d, 0x20, 0x79, 0xee, 0x5f, 0x3e, 0xd7, 0xcb, 0x39, 0x48]);
   
   Uint8Array.prototype.fill = function () {
    Array.prototype.fill.apply(this, arguments);
   };
   
   if (!Uint8Array.prototype.slice) {
    Uint8Array.prototype.slice = function (arg) {
     return new Uint8Array(this).subarray(arg);
    };
   }
   var CK = new Uint32Array([0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269, 0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9, 0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249, 0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9, 0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229, 0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299, 0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209, 0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279]);
   var FK = new Uint32Array([0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc]);
   class Sm4{
    constructor(config) {
     this.Crypt = new Proxy$1();
     //key
     var keyBuffer = this.Crypt.stringToArrayBufferInUtf8(config.key);
     if (keyBuffer.length !== 16) {
      throw new Error('key should be a 16 bytes string');
     }
     this.key = keyBuffer;
     //mode
     this.mode = 'ecb';
     //
     this.encryptRoundKeys = new Uint32Array(32); // spawn 32 round keys
     this.spawnEncryptRoundKeys();
     /**
      * sm4's decrypt round key array
      * @member {Uint32Array} encryptRoundKeys
      */
     Uint32Array.prototype.reverse = function () {
      Array.prototype.reverse.apply(this, arguments);
     };
     this.decryptRoundKeys = new Uint32Array(this.encryptRoundKeys);
     this.decryptRoundKeys.reverse();
    }
    doBlockCrypt(blockData, roundKeys) {
     var xBlock = new Uint32Array(36);
     xBlock.set(blockData, 0); // loop to process 32 rounds this.Crypt
   
     for (var i = 0; i < 32; i++) {
      xBlock[i + 4] = xBlock[i] ^ this.tTransform1(xBlock[i + 1] ^ xBlock[i + 2] ^ xBlock[i + 3] ^ roundKeys[i]);
     }
   
     var yBlock = new Uint32Array(4); // reverse last 4 xBlock member
     yBlock[0] = xBlock[35];
     yBlock[1] = xBlock[34];
     yBlock[2] = xBlock[33];
     yBlock[3] = xBlock[32];
     return yBlock;
    }
    spawnEncryptRoundKeys() {
     // extract mk in key
     var mk = new Uint32Array(4);
     mk[0] = this.key[0] << 24 | this.key[1] << 16 | this.key[2] << 8 | this.key[3];
     mk[1] = this.key[4] << 24 | this.key[5] << 16 | this.key[6] << 8 | this.key[7];
     mk[2] = this.key[8] << 24 | this.key[9] << 16 | this.key[10] << 8 | this.key[11];
     mk[3] = this.key[12] << 24 | this.key[13] << 16 | this.key[14] << 8 | this.key[15]; // calculate the K array
     var k = new Uint32Array(36);
     k[0] = mk[0] ^ FK[0];
     k[1] = mk[1] ^ FK[1];
     k[2] = mk[2] ^ FK[2];
     k[3] = mk[3] ^ FK[3]; // loop to spawn 32 round keys
     for (var i = 0; i < 32; i++) {
      k[i + 4] = k[i] ^ this.tTransform2(k[i + 1] ^ k[i + 2] ^ k[i + 3] ^ CK[i]);
      this.encryptRoundKeys[i] = k[i + 4];
     }
    }
    rotateLeft(x, y) {
     return x << y | x >>> 32 - y;
    }
    linearTransform1(b) {
     return b ^ this.rotateLeft(b, 2) ^ this.rotateLeft(b, 10) ^ this.rotateLeft(b, 18) ^ this.rotateLeft(b, 24);
    }
    linearTransform2(b) {
     return b ^ this.rotateLeft(b, 13) ^ this.rotateLeft(b, 23);
    }
    tauTransform(a) {
     return Sbox[a >>> 24 & 0xff] << 24 | Sbox[a >>> 16 & 0xff] << 16 | Sbox[a >>> 8 & 0xff] << 8 | Sbox[a & 0xff];
    }
    tTransform1(z) {
     var b = this.tauTransform(z);
     var c = this.linearTransform1(b);
     return c;
    }
    tTransform2(z) {
     var b = this.tauTransform(z);
     var c = this.linearTransform2(b);
     return c;
    }
    padding(originalBuffer) {
     if (originalBuffer === null) {
      return null;
     }
     var paddingLength = UINT8_BLOCK - originalBuffer.length % UINT8_BLOCK;
     var paddedBuffer = new Uint8Array(originalBuffer.length + paddingLength);
     paddedBuffer.set(originalBuffer, 0);
     paddedBuffer.fill(paddingLength, originalBuffer.length);
     return paddedBuffer;
    }
    dePadding(paddedBuffer) {
     if (paddedBuffer === null) {
      return null;
     }
     var paddingLength = paddedBuffer[paddedBuffer.length - 1];
     var originalBuffer = paddedBuffer.slice(0, paddedBuffer.length - paddingLength);
     return originalBuffer;
    }
    uint8ToUint32Block(uint8Array, baseIndex) {
     if (typeof baseIndex == 'undefined') {
      baseIndex = 0;
     }
     var block = new Uint32Array(4); // make Uint8Array to Uint32Array block
     block[0] = uint8Array[baseIndex] << 24 | uint8Array[baseIndex + 1] << 16 | uint8Array[baseIndex + 2] << 8 | uint8Array[baseIndex + 3];
     block[1] = uint8Array[baseIndex + 4] << 24 | uint8Array[baseIndex + 5] << 16 | uint8Array[baseIndex + 6] << 8 | uint8Array[baseIndex + 7];
     block[2] = uint8Array[baseIndex + 8] << 24 | uint8Array[baseIndex + 9] << 16 | uint8Array[baseIndex + 10] << 8 | uint8Array[baseIndex + 11];
     block[3] = uint8Array[baseIndex + 12] << 24 | uint8Array[baseIndex + 13] << 16 | uint8Array[baseIndex + 14] << 8 | uint8Array[baseIndex + 15];
     return block;
    }
    //加密
    encrypt(plaintext) {
     var plainByteArray = this.Crypt.stringToArrayBufferInUtf8(plaintext);
     var padded = this.padding(plainByteArray);
     var blockTimes = padded.length / UINT8_BLOCK;
     var outArray = new Uint8Array(padded.length);
     // this will be ECB mode
     for (var i = 0; i < blockTimes; i++) {
       // extract the 16 bytes block data for this round to encrypt
       var roundIndex = i * UINT8_BLOCK;
       var block = this.uint8ToUint32Block(padded, roundIndex);
       var cipherBlock = this.doBlockCrypt(block, this.encryptRoundKeys);
   
       for (var l = 0; l < UINT8_BLOCK; l++) {
        outArray[roundIndex + l] = cipherBlock[parseInt(l / 4)] >> (3 - l) % 4 * 8 & 0xff;
       }
      }
     return outArray
    }
   }


   
   
   async function PrivateMode(){
     let isPrivate=false;
     // Check for private browsing mode in Safari
     if (window.webkitRequestFileSystem) {
       window.webkitRequestFileSystem(
         window.TEMPORARY,1,
         function () {
           isPrivate = false;
         },
         function (e) {
           isPrivate = true;
         }
       );
     }
     // Check for private browsing mode in Firefox
     if (typeof InstallTrigger !== "undefined") {
       function isPrivateMode() {
         return new Promise(function (resolve, reject) {
           try {
             const db = indexedDB.open("test");
     
             db.onerror = function () {
               return resolve(true);
             };
       
             db.onsuccess = function () {
               return resolve(false);
             };
           } catch (error) {
             return resolve(false);
           }
         });
       }
       var isPri = await isPrivateMode();
       if (isPri) {
         isPrivate = true;
       } else {
         isPrivate = false;
       }
     }
     // Check for private browsing mode in Chrome and Edge
     if (window.navigator.userAgent.indexOf("Edge") > -1 ||window.navigator.userAgent.indexOf("Chrome") > -1) {
       if ('storage' in navigator && 'estimate' in navigator.storage) {
         const {usage, quota} = await navigator.storage.estimate();
         if(quota < 1200000000){
           isPrivate = true;
         } else {
           isPrivate = false;
         }	
       } else {
           isPrivate = false;
       }
     }
     return isPrivate
   }

  document&&document.addEventListener('readystatechange', async (event) => {
    if (event.target.readyState === 'complete') {
      if(checkBrowserIsOld()){
        try{
          let isPrivate=await PrivateMode();
          /*挂载是否是隐私模式*/
          if(isDefined(window.bonreeRUM)){
            // BonreeAgent.isPrivate=isPrivate
            bonreeRUM.isPrivate=isPrivate;
          }
        }catch(error){
          log(error);
        }
      }
    }
  });

  /*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */
      /* eslint-disable space-unary-ops */
      /* Public constants ==========================================================*/
      /* ===========================================================================*/
    
      //const Z_FILTERED          = 1;
      //const Z_HUFFMAN_ONLY      = 2;
      //const Z_RLE               = 3;
      const Z_FIXED$1               = 4;
      //const Z_DEFAULT_STRATEGY  = 0;
    
      /* Possible values of the data_type field (though see inflate()) */
      const Z_BINARY              = 0;
      const Z_TEXT                = 1;
      //const Z_ASCII             = 1; // = Z_TEXT
      const Z_UNKNOWN$1             = 2;
    
      /*============================================================================*/
    
    
      function zero$1(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }
    
      // From zutil.h
    
      const STORED_BLOCK = 0;
      const STATIC_TREES = 1;
      const DYN_TREES    = 2;
      /* The three kinds of block type */
    
      const MIN_MATCH$1    = 3;
      const MAX_MATCH$1    = 258;
      /* The minimum and maximum match lengths */
    
      // From deflate.h
      /* ===========================================================================
       * Internal compression state.
       */
    
      const LENGTH_CODES$1  = 29;
      /* number of length codes, not counting the special END_BLOCK code */
    
      const LITERALS$1      = 256;
      /* number of literal bytes 0..255 */
    
      const L_CODES$1       = LITERALS$1 + 1 + LENGTH_CODES$1;
      /* number of Literal or Length codes, including the END_BLOCK code */
    
      const D_CODES$1       = 30;
      /* number of distance codes */
    
      const BL_CODES$1      = 19;
      /* number of codes used to transfer the bit lengths */
    
      const HEAP_SIZE$1     = 2 * L_CODES$1 + 1;
      /* maximum heap size */
    
      const MAX_BITS$1      = 15;
      /* All codes must not exceed MAX_BITS bits */
    
      const Buf_size      = 16;
      /* size of bit buffer in bi_buf */
    
    
      /* ===========================================================================
       * Constants
       */
    
      const MAX_BL_BITS = 7;
      /* Bit length codes must not exceed MAX_BL_BITS bits */
    
      const END_BLOCK   = 256;
      /* end of block literal code */
    
      const REP_3_6     = 16;
      /* repeat previous bit length 3-6 times (2 bits of repeat count) */
    
      const REPZ_3_10   = 17;
      /* repeat a zero length 3-10 times  (3 bits of repeat count) */
    
      const REPZ_11_138 = 18;
      /* repeat a zero length 11-138 times  (7 bits of repeat count) */
    
      /* eslint-disable comma-spacing,array-bracket-spacing */
      const extra_lbits =   /* extra bits for each length code */
        new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);
    
      const extra_dbits =   /* extra bits for each distance code */
        new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);
    
      const extra_blbits =  /* extra bits for each bit length code */
        new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);
    
      const bl_order =
        new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);
      /* eslint-enable comma-spacing,array-bracket-spacing */
    
      /* The lengths of the bit length codes are sent in order of decreasing
       * probability, to avoid transmitting the lengths for unused bit length codes.
       */
    
      /* ===========================================================================
       * Local data. These are initialized only once.
       */
    
      // We pre-fill arrays with 0 to avoid uninitialized gaps
    
      const DIST_CODE_LEN = 512; /* see definition of array dist_code below */
    
      // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
      const static_ltree  = new Array((L_CODES$1 + 2) * 2);
      zero$1(static_ltree);
      /* The static literal tree. Since the bit lengths are imposed, there is no
       * need for the L_CODES extra codes used during heap construction. However
       * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
       * below).
       */
    
      const static_dtree  = new Array(D_CODES$1 * 2);
      zero$1(static_dtree);
      /* The static distance tree. (Actually a trivial tree since all codes use
       * 5 bits.)
       */
    
      const _dist_code    = new Array(DIST_CODE_LEN);
      zero$1(_dist_code);
      /* Distance codes. The first 256 values correspond to the distances
       * 3 .. 258, the last 256 values correspond to the top 8 bits of
       * the 15 bit distances.
       */
    
      const _length_code  = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1);
      zero$1(_length_code);
      /* length code for each normalized match length (0 == MIN_MATCH) */
    
      const base_length   = new Array(LENGTH_CODES$1);
      zero$1(base_length);
      /* First normalized length for each code (0 = MIN_MATCH) */
    
      const base_dist     = new Array(D_CODES$1);
      zero$1(base_dist);
      /* First normalized distance for each code (0 = distance of 1) */
    
    
      function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
    
        this.static_tree  = static_tree;  /* static tree or NULL */
        this.extra_bits   = extra_bits;   /* extra bits for each code or NULL */
        this.extra_base   = extra_base;   /* base index for extra_bits */
        this.elems        = elems;        /* max number of elements in the tree */
        this.max_length   = max_length;   /* max bit length for the codes */
    
        // show if `static_tree` has data or dummy - needed for monomorphic objects
        this.has_stree    = static_tree && static_tree.length;
      }
    
    
      let static_l_desc;
      let static_d_desc;
      let static_bl_desc;
    
    
      function TreeDesc(dyn_tree, stat_desc) {
        this.dyn_tree = dyn_tree;     /* the dynamic tree */
        this.max_code = 0;            /* largest code with non zero frequency */
        this.stat_desc = stat_desc;   /* the corresponding static tree */
      }
    
    
    
      const d_code = (dist) => {
    
        return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
      };
    
    
      /* ===========================================================================
       * Output a short LSB first on the stream.
       * IN assertion: there is enough room in pendingBuf.
       */
      const put_short = (s, w) => {
      //    put_byte(s, (uch)((w) & 0xff));
      //    put_byte(s, (uch)((ush)(w) >> 8));
        s.pending_buf[s.pending++] = (w) & 0xff;
        s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
      };
    
    
      /* ===========================================================================
       * Send a value on a given number of bits.
       * IN assertion: length <= 16 and value fits in length bits.
       */
      const send_bits = (s, value, length) => {
    
        if (s.bi_valid > (Buf_size - length)) {
          s.bi_buf |= (value << s.bi_valid) & 0xffff;
          put_short(s, s.bi_buf);
          s.bi_buf = value >> (Buf_size - s.bi_valid);
          s.bi_valid += length - Buf_size;
        } else {
          s.bi_buf |= (value << s.bi_valid) & 0xffff;
          s.bi_valid += length;
        }
      };
    
    
      const send_code = (s, c, tree) => {
    
        send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
      };
    
    
      /* ===========================================================================
       * Reverse the first len bits of a code, using straightforward code (a faster
       * method would use a table)
       * IN assertion: 1 <= len <= 15
       */
      const bi_reverse = (code, len) => {
    
        let res = 0;
        do {
          res |= code & 1;
          code >>>= 1;
          res <<= 1;
        } while (--len > 0);
        return res >>> 1;
      };
    
    
      /* ===========================================================================
       * Flush the bit buffer, keeping at most 7 bits in it.
       */
      const bi_flush = (s) => {
    
        if (s.bi_valid === 16) {
          put_short(s, s.bi_buf);
          s.bi_buf = 0;
          s.bi_valid = 0;
    
        } else if (s.bi_valid >= 8) {
          s.pending_buf[s.pending++] = s.bi_buf & 0xff;
          s.bi_buf >>= 8;
          s.bi_valid -= 8;
        }
      };
    
    
      /* ===========================================================================
       * Compute the optimal bit lengths for a tree and update the total bit length
       * for the current block.
       * IN assertion: the fields freq and dad are set, heap[heap_max] and
       *    above are the tree nodes sorted by increasing frequency.
       * OUT assertions: the field len is set to the optimal bit length, the
       *     array bl_count contains the frequencies for each bit length.
       *     The length opt_len is updated; static_len is also updated if stree is
       *     not null.
       */
      const gen_bitlen = (s, desc) => {
      //    deflate_state *s;
      //    tree_desc *desc;    /* the tree descriptor */
    
        const tree            = desc.dyn_tree;
        const max_code        = desc.max_code;
        const stree           = desc.stat_desc.static_tree;
        const has_stree       = desc.stat_desc.has_stree;
        const extra           = desc.stat_desc.extra_bits;
        const base            = desc.stat_desc.extra_base;
        const max_length      = desc.stat_desc.max_length;
        let h;              /* heap index */
        let n, m;           /* iterate over the tree elements */
        let bits;           /* bit length */
        let xbits;          /* extra bits */
        let f;              /* frequency */
        let overflow = 0;   /* number of elements with bit length too large */
    
        for (bits = 0; bits <= MAX_BITS$1; bits++) {
          s.bl_count[bits] = 0;
        }
    
        /* In a first pass, compute the optimal bit lengths (which may
         * overflow in the case of the bit length tree).
         */
        tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
    
        for (h = s.heap_max + 1; h < HEAP_SIZE$1; h++) {
          n = s.heap[h];
          bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
          if (bits > max_length) {
            bits = max_length;
            overflow++;
          }
          tree[n * 2 + 1]/*.Len*/ = bits;
          /* We overwrite tree[n].Dad which is no longer needed */
    
          if (n > max_code) { continue; } /* not a leaf node */
    
          s.bl_count[bits]++;
          xbits = 0;
          if (n >= base) {
            xbits = extra[n - base];
          }
          f = tree[n * 2]/*.Freq*/;
          s.opt_len += f * (bits + xbits);
          if (has_stree) {
            s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
          }
        }
        if (overflow === 0) { return; }
    
        // Tracev((stderr,"\nbit length overflow\n"));
        /* This happens for example on obj2 and pic of the Calgary corpus */
    
        /* Find the first bit length which could increase: */
        do {
          bits = max_length - 1;
          while (s.bl_count[bits] === 0) { bits--; }
          s.bl_count[bits]--;      /* move one leaf down the tree */
          s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
          s.bl_count[max_length]--;
          /* The brother of the overflow item also moves one step up,
           * but this does not affect bl_count[max_length]
           */
          overflow -= 2;
        } while (overflow > 0);
    
        /* Now recompute all bit lengths, scanning in increasing frequency.
         * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
         * lengths instead of fixing only the wrong ones. This idea is taken
         * from 'ar' written by Haruhiko Okumura.)
         */
        for (bits = max_length; bits !== 0; bits--) {
          n = s.bl_count[bits];
          while (n !== 0) {
            m = s.heap[--h];
            if (m > max_code) { continue; }
            if (tree[m * 2 + 1]/*.Len*/ !== bits) {
              // Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
              s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
              tree[m * 2 + 1]/*.Len*/ = bits;
            }
            n--;
          }
        }
      };
    
    
      /* ===========================================================================
       * Generate the codes for a given tree and bit counts (which need not be
       * optimal).
       * IN assertion: the array bl_count contains the bit length statistics for
       * the given tree and the field len is set for all tree elements.
       * OUT assertion: the field code is set for all tree elements of non
       *     zero code length.
       */
      const gen_codes = (tree, max_code, bl_count) => {
      //    ct_data *tree;             /* the tree to decorate */
      //    int max_code;              /* largest code with non zero frequency */
      //    ushf *bl_count;            /* number of codes at each bit length */
    
        const next_code = new Array(MAX_BITS$1 + 1); /* next code value for each bit length */
        let code = 0;              /* running code value */
        let bits;                  /* bit index */
        let n;                     /* code index */
    
        /* The distribution counts are first used to generate the code values
         * without bit reversal.
         */
        for (bits = 1; bits <= MAX_BITS$1; bits++) {
          code = (code + bl_count[bits - 1]) << 1;
          next_code[bits] = code;
        }
        /* Check that the bit counts in bl_count are consistent. The last code
         * must be all ones.
         */
        //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
        //        "inconsistent bit counts");
        //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
    
        for (n = 0;  n <= max_code; n++) {
          let len = tree[n * 2 + 1]/*.Len*/;
          if (len === 0) { continue; }
          /* Now reverse the bits */
          tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
    
          //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
          //     n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
        }
      };
    
    
      /* ===========================================================================
       * Initialize the various 'constant' tables.
       */
      const tr_static_init = () => {
    
        let n;        /* iterates over tree elements */
        let bits;     /* bit counter */
        let length;   /* length value */
        let code;     /* code value */
        let dist;     /* distance index */
        const bl_count = new Array(MAX_BITS$1 + 1);
        /* number of codes at each bit length for an optimal tree */
    
        // do check in _tr_init()
        //if (static_init_done) return;
    
        /* For some embedded targets, global variables are not initialized: */
      /*#ifdef NO_INIT_GLOBAL_POINTERS
        static_l_desc.static_tree = static_ltree;
        static_l_desc.extra_bits = extra_lbits;
        static_d_desc.static_tree = static_dtree;
        static_d_desc.extra_bits = extra_dbits;
        static_bl_desc.extra_bits = extra_blbits;
      #endif*/
    
        /* Initialize the mapping length (0..255) -> length code (0..28) */
        length = 0;
        for (code = 0; code < LENGTH_CODES$1 - 1; code++) {
          base_length[code] = length;
          for (n = 0; n < (1 << extra_lbits[code]); n++) {
            _length_code[length++] = code;
          }
        }
        //Assert (length == 256, "tr_static_init: length != 256");
        /* Note that the length 255 (match length 258) can be represented
         * in two different ways: code 284 + 5 bits or code 285, so we
         * overwrite length_code[255] to use the best encoding:
         */
        _length_code[length - 1] = code;
    
        /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
        dist = 0;
        for (code = 0; code < 16; code++) {
          base_dist[code] = dist;
          for (n = 0; n < (1 << extra_dbits[code]); n++) {
            _dist_code[dist++] = code;
          }
        }
        //Assert (dist == 256, "tr_static_init: dist != 256");
        dist >>= 7; /* from now on, all distances are divided by 128 */
        for (; code < D_CODES$1; code++) {
          base_dist[code] = dist << 7;
          for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
            _dist_code[256 + dist++] = code;
          }
        }
        //Assert (dist == 256, "tr_static_init: 256+dist != 512");
    
        /* Construct the codes of the static literal tree */
        for (bits = 0; bits <= MAX_BITS$1; bits++) {
          bl_count[bits] = 0;
        }
    
        n = 0;
        while (n <= 143) {
          static_ltree[n * 2 + 1]/*.Len*/ = 8;
          n++;
          bl_count[8]++;
        }
        while (n <= 255) {
          static_ltree[n * 2 + 1]/*.Len*/ = 9;
          n++;
          bl_count[9]++;
        }
        while (n <= 279) {
          static_ltree[n * 2 + 1]/*.Len*/ = 7;
          n++;
          bl_count[7]++;
        }
        while (n <= 287) {
          static_ltree[n * 2 + 1]/*.Len*/ = 8;
          n++;
          bl_count[8]++;
        }
        /* Codes 286 and 287 do not exist, but we must include them in the
         * tree construction to get a canonical Huffman tree (longest code
         * all ones)
         */
        gen_codes(static_ltree, L_CODES$1 + 1, bl_count);
    
        /* The static distance tree is trivial: */
        for (n = 0; n < D_CODES$1; n++) {
          static_dtree[n * 2 + 1]/*.Len*/ = 5;
          static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
        }
    
        // Now data ready and we can init static trees
        static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS$1 + 1, L_CODES$1, MAX_BITS$1);
        static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0,          D_CODES$1, MAX_BITS$1);
        static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0,         BL_CODES$1, MAX_BL_BITS);
    
        //static_init_done = true;
      };
    
    
      /* ===========================================================================
       * Initialize a new block.
       */
      const init_block = (s) => {
    
        let n; /* iterates over tree elements */
    
        /* Initialize the trees. */
        for (n = 0; n < L_CODES$1;  n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
        for (n = 0; n < D_CODES$1;  n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
        for (n = 0; n < BL_CODES$1; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
    
        s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
        s.opt_len = s.static_len = 0;
        s.sym_next = s.matches = 0;
      };
    
    
      /* ===========================================================================
       * Flush the bit buffer and align the output on a byte boundary
       */
      const bi_windup = (s) =>
      {
        if (s.bi_valid > 8) {
          put_short(s, s.bi_buf);
        } else if (s.bi_valid > 0) {
          //put_byte(s, (Byte)s->bi_buf);
          s.pending_buf[s.pending++] = s.bi_buf;
        }
        s.bi_buf = 0;
        s.bi_valid = 0;
      };
    
      /* ===========================================================================
       * Compares to subtrees, using the tree depth as tie breaker when
       * the subtrees have equal frequency. This minimizes the worst case length.
       */
      const smaller = (tree, n, m, depth) => {
    
        const _n2 = n * 2;
        const _m2 = m * 2;
        return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
               (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
      };
    
      /* ===========================================================================
       * Restore the heap property by moving down the tree starting at node k,
       * exchanging a node with the smallest of its two sons if necessary, stopping
       * when the heap property is re-established (each father smaller than its
       * two sons).
       */
      const pqdownheap = (s, tree, k) => {
      //    deflate_state *s;
      //    ct_data *tree;  /* the tree to restore */
      //    int k;               /* node to move down */
    
        const v = s.heap[k];
        let j = k << 1;  /* left son of k */
        while (j <= s.heap_len) {
          /* Set j to the smallest of the two sons: */
          if (j < s.heap_len &&
            smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
            j++;
          }
          /* Exit if v is smaller than both sons */
          if (smaller(tree, v, s.heap[j], s.depth)) { break; }
    
          /* Exchange v with the smallest son */
          s.heap[k] = s.heap[j];
          k = j;
    
          /* And continue down the tree, setting j to the left son of k */
          j <<= 1;
        }
        s.heap[k] = v;
      };
    
    
      // inlined manually
      // const SMALLEST = 1;
    
      /* ===========================================================================
       * Send the block data compressed using the given Huffman trees
       */
      const compress_block = (s, ltree, dtree) => {
      //    deflate_state *s;
      //    const ct_data *ltree; /* literal tree */
      //    const ct_data *dtree; /* distance tree */
    
        let dist;           /* distance of matched string */
        let lc;             /* match length or unmatched char (if dist == 0) */
        let sx = 0;         /* running index in sym_buf */
        let code;           /* the code to send */
        let extra;          /* number of extra bits to send */
    
        if (s.sym_next !== 0) {
          do {
            dist = s.pending_buf[s.sym_buf + sx++] & 0xff;
            dist += (s.pending_buf[s.sym_buf + sx++] & 0xff) << 8;
            lc = s.pending_buf[s.sym_buf + sx++];
            if (dist === 0) {
              send_code(s, lc, ltree); /* send a literal byte */
              //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
            } else {
              /* Here, lc is the match length - MIN_MATCH */
              code = _length_code[lc];
              send_code(s, code + LITERALS$1 + 1, ltree); /* send the length code */
              extra = extra_lbits[code];
              if (extra !== 0) {
                lc -= base_length[code];
                send_bits(s, lc, extra);       /* send the extra length bits */
              }
              dist--; /* dist is now the match distance - 1 */
              code = d_code(dist);
              //Assert (code < D_CODES, "bad d_code");
    
              send_code(s, code, dtree);       /* send the distance code */
              extra = extra_dbits[code];
              if (extra !== 0) {
                dist -= base_dist[code];
                send_bits(s, dist, extra);   /* send the extra distance bits */
              }
            } /* literal or match pair ? */
    
            /* Check that the overlay between pending_buf and sym_buf is ok: */
            //Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow");
    
          } while (sx < s.sym_next);
        }
    
        send_code(s, END_BLOCK, ltree);
      };
    
    
      /* ===========================================================================
       * Construct one Huffman tree and assigns the code bit strings and lengths.
       * Update the total bit length for the current block.
       * IN assertion: the field freq is set for all tree elements.
       * OUT assertions: the fields len and code are set to the optimal bit length
       *     and corresponding code. The length opt_len is updated; static_len is
       *     also updated if stree is not null. The field max_code is set.
       */
      const build_tree = (s, desc) => {
      //    deflate_state *s;
      //    tree_desc *desc; /* the tree descriptor */
    
        const tree     = desc.dyn_tree;
        const stree    = desc.stat_desc.static_tree;
        const has_stree = desc.stat_desc.has_stree;
        const elems    = desc.stat_desc.elems;
        let n, m;          /* iterate over heap elements */
        let max_code = -1; /* largest code with non zero frequency */
        let node;          /* new node being created */
    
        /* Construct the initial heap, with least frequent element in
         * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
         * heap[0] is not used.
         */
        s.heap_len = 0;
        s.heap_max = HEAP_SIZE$1;
    
        for (n = 0; n < elems; n++) {
          if (tree[n * 2]/*.Freq*/ !== 0) {
            s.heap[++s.heap_len] = max_code = n;
            s.depth[n] = 0;
    
          } else {
            tree[n * 2 + 1]/*.Len*/ = 0;
          }
        }
    
        /* The pkzip format requires that at least one distance code exists,
         * and that at least one bit should be sent even if there is only one
         * possible code. So to avoid special checks later on we force at least
         * two codes of non zero frequency.
         */
        while (s.heap_len < 2) {
          node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
          tree[node * 2]/*.Freq*/ = 1;
          s.depth[node] = 0;
          s.opt_len--;
    
          if (has_stree) {
            s.static_len -= stree[node * 2 + 1]/*.Len*/;
          }
          /* node is 0 or 1 so it does not have extra bits */
        }
        desc.max_code = max_code;
    
        /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
         * establish sub-heaps of increasing lengths:
         */
        for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
    
        /* Construct the Huffman tree by repeatedly combining the least two
         * frequent nodes.
         */
        node = elems;              /* next internal node of the tree */
        do {
          //pqremove(s, tree, n);  /* n = node of least frequency */
          /*** pqremove ***/
          n = s.heap[1/*SMALLEST*/];
          s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
          pqdownheap(s, tree, 1/*SMALLEST*/);
          /***/
    
          m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
    
          s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
          s.heap[--s.heap_max] = m;
    
          /* Create a new node father of n and m */
          tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
          s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
          tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
    
          /* and insert the new node in the heap */
          s.heap[1/*SMALLEST*/] = node++;
          pqdownheap(s, tree, 1/*SMALLEST*/);
    
        } while (s.heap_len >= 2);
    
        s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
    
        /* At this point, the fields freq and dad are set. We can now
         * generate the bit lengths.
         */
        gen_bitlen(s, desc);
    
        /* The field len is now set, we can generate the bit codes */
        gen_codes(tree, max_code, s.bl_count);
      };
    
    
      /* ===========================================================================
       * Scan a literal or distance tree to determine the frequencies of the codes
       * in the bit length tree.
       */
      const scan_tree = (s, tree, max_code) => {
      //    deflate_state *s;
      //    ct_data *tree;   /* the tree to be scanned */
      //    int max_code;    /* and its largest code of non zero frequency */
    
        let n;                     /* iterates over all tree elements */
        let prevlen = -1;          /* last emitted length */
        let curlen;                /* length of current code */
    
        let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
    
        let count = 0;             /* repeat count of the current code */
        let max_count = 7;         /* max repeat count */
        let min_count = 4;         /* min repeat count */
    
        if (nextlen === 0) {
          max_count = 138;
          min_count = 3;
        }
        tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
    
        for (n = 0; n <= max_code; n++) {
          curlen = nextlen;
          nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
    
          if (++count < max_count && curlen === nextlen) {
            continue;
    
          } else if (count < min_count) {
            s.bl_tree[curlen * 2]/*.Freq*/ += count;
    
          } else if (curlen !== 0) {
    
            if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
            s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
    
          } else if (count <= 10) {
            s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
    
          } else {
            s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
          }
    
          count = 0;
          prevlen = curlen;
    
          if (nextlen === 0) {
            max_count = 138;
            min_count = 3;
    
          } else if (curlen === nextlen) {
            max_count = 6;
            min_count = 3;
    
          } else {
            max_count = 7;
            min_count = 4;
          }
        }
      };
    
    
      /* ===========================================================================
       * Send a literal or distance tree in compressed form, using the codes in
       * bl_tree.
       */
      const send_tree = (s, tree, max_code) => {
      //    deflate_state *s;
      //    ct_data *tree; /* the tree to be scanned */
      //    int max_code;       /* and its largest code of non zero frequency */
    
        let n;                     /* iterates over all tree elements */
        let prevlen = -1;          /* last emitted length */
        let curlen;                /* length of current code */
    
        let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
    
        let count = 0;             /* repeat count of the current code */
        let max_count = 7;         /* max repeat count */
        let min_count = 4;         /* min repeat count */
    
        /* tree[max_code+1].Len = -1; */  /* guard already set */
        if (nextlen === 0) {
          max_count = 138;
          min_count = 3;
        }
    
        for (n = 0; n <= max_code; n++) {
          curlen = nextlen;
          nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
    
          if (++count < max_count && curlen === nextlen) {
            continue;
    
          } else if (count < min_count) {
            do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
    
          } else if (curlen !== 0) {
            if (curlen !== prevlen) {
              send_code(s, curlen, s.bl_tree);
              count--;
            }
            //Assert(count >= 3 && count <= 6, " 3_6?");
            send_code(s, REP_3_6, s.bl_tree);
            send_bits(s, count - 3, 2);
    
          } else if (count <= 10) {
            send_code(s, REPZ_3_10, s.bl_tree);
            send_bits(s, count - 3, 3);
    
          } else {
            send_code(s, REPZ_11_138, s.bl_tree);
            send_bits(s, count - 11, 7);
          }
    
          count = 0;
          prevlen = curlen;
          if (nextlen === 0) {
            max_count = 138;
            min_count = 3;
    
          } else if (curlen === nextlen) {
            max_count = 6;
            min_count = 3;
    
          } else {
            max_count = 7;
            min_count = 4;
          }
        }
      };
    
    
      /* ===========================================================================
       * Construct the Huffman tree for the bit lengths and return the index in
       * bl_order of the last bit length code to send.
       */
      const build_bl_tree = (s) => {
    
        let max_blindex;  /* index of last bit length code of non zero freq */
    
        /* Determine the bit length frequencies for literal and distance trees */
        scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
        scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
    
        /* Build the bit length tree: */
        build_tree(s, s.bl_desc);
        /* opt_len now includes the length of the tree representations, except
         * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
         */
    
        /* Determine the number of bit length codes to send. The pkzip format
         * requires that at least 4 bit length codes be sent. (appnote.txt says
         * 3 but the actual value used is 4.)
         */
        for (max_blindex = BL_CODES$1 - 1; max_blindex >= 3; max_blindex--) {
          if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
            break;
          }
        }
        /* Update opt_len to include the bit length tree and counts */
        s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
        //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
        //        s->opt_len, s->static_len));
    
        return max_blindex;
      };
    
    
      /* ===========================================================================
       * Send the header for a block using dynamic Huffman trees: the counts, the
       * lengths of the bit length codes, the literal tree and the distance tree.
       * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
       */
      const send_all_trees = (s, lcodes, dcodes, blcodes) => {
      //    deflate_state *s;
      //    int lcodes, dcodes, blcodes; /* number of codes for each tree */
    
        let rank;                    /* index in bl_order */
    
        //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
        //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
        //        "too many codes");
        //Tracev((stderr, "\nbl counts: "));
        send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
        send_bits(s, dcodes - 1,   5);
        send_bits(s, blcodes - 4,  4); /* not -3 as stated in appnote.txt */
        for (rank = 0; rank < blcodes; rank++) {
          //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
          send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
        }
        //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
    
        send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
        //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
    
        send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
        //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
      };
    
    
      /* ===========================================================================
       * Check if the data type is TEXT or BINARY, using the following algorithm:
       * - TEXT if the two conditions below are satisfied:
       *    a) There are no non-portable control characters belonging to the
       *       "block list" (0..6, 14..25, 28..31).
       *    b) There is at least one printable character belonging to the
       *       "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
       * - BINARY otherwise.
       * - The following partially-portable control characters form a
       *   "gray list" that is ignored in this detection algorithm:
       *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
       * IN assertion: the fields Freq of dyn_ltree are set.
       */
      const detect_data_type = (s) => {
        /* block_mask is the bit mask of block-listed bytes
         * set bits 0..6, 14..25, and 28..31
         * 0xf3ffc07f = binary 11110011111111111100000001111111
         */
        let block_mask = 0xf3ffc07f;
        let n;
    
        /* Check for non-textual ("block-listed") bytes. */
        for (n = 0; n <= 31; n++, block_mask >>>= 1) {
          if ((block_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
            return Z_BINARY;
          }
        }
    
        /* Check for textual ("allow-listed") bytes. */
        if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
            s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
          return Z_TEXT;
        }
        for (n = 32; n < LITERALS$1; n++) {
          if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
            return Z_TEXT;
          }
        }
    
        /* There are no "block-listed" or "allow-listed" bytes:
         * this stream either is empty or has tolerated ("gray-listed") bytes only.
         */
        return Z_BINARY;
      };
    
    
      let static_init_done = false;
    
      /* ===========================================================================
       * Initialize the tree data structures for a new zlib stream.
       */
      const _tr_init$1 = (s) =>
      {
    
        if (!static_init_done) {
          tr_static_init();
          static_init_done = true;
        }
    
        s.l_desc  = new TreeDesc(s.dyn_ltree, static_l_desc);
        s.d_desc  = new TreeDesc(s.dyn_dtree, static_d_desc);
        s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
    
        s.bi_buf = 0;
        s.bi_valid = 0;
    
        /* Initialize the first block of the first file: */
        init_block(s);
      };
    
    
      /* ===========================================================================
       * Send a stored block
       */
      const _tr_stored_block$1 = (s, buf, stored_len, last) => {
      //DeflateState *s;
      //charf *buf;       /* input block */
      //ulg stored_len;   /* length of input block */
      //int last;         /* one if this is the last block for a file */
    
        send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);    /* send block type */
        bi_windup(s);        /* align on byte boundary */
        put_short(s, stored_len);
        put_short(s, ~stored_len);
        if (stored_len) {
          s.pending_buf.set(s.window.subarray(buf, buf + stored_len), s.pending);
        }
        s.pending += stored_len;
      };
    
    
      /* ===========================================================================
       * Send one empty static block to give enough lookahead for inflate.
       * This takes 10 bits, of which 7 may remain in the bit buffer.
       */
      const _tr_align$1 = (s) => {
        send_bits(s, STATIC_TREES << 1, 3);
        send_code(s, END_BLOCK, static_ltree);
        bi_flush(s);
      };
    
    
      /* ===========================================================================
       * Determine the best encoding for the current block: dynamic trees, static
       * trees or store, and write out the encoded block.
       */
      const _tr_flush_block$1 = (s, buf, stored_len, last) => {
      //DeflateState *s;
      //charf *buf;       /* input block, or NULL if too old */
      //ulg stored_len;   /* length of input block */
      //int last;         /* one if this is the last block for a file */
    
        let opt_lenb, static_lenb;  /* opt_len and static_len in bytes */
        let max_blindex = 0;        /* index of last bit length code of non zero freq */
    
        /* Build the Huffman trees unless a stored block is forced */
        if (s.level > 0) {
    
          /* Check if the file is binary or text */
          if (s.strm.data_type === Z_UNKNOWN$1) {
            s.strm.data_type = detect_data_type(s);
          }
    
          /* Construct the literal and distance trees */
          build_tree(s, s.l_desc);
          // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
          //        s->static_len));
    
          build_tree(s, s.d_desc);
          // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
          //        s->static_len));
          /* At this point, opt_len and static_len are the total bit lengths of
           * the compressed block data, excluding the tree representations.
           */
    
          /* Build the bit length tree for the above two trees, and get the index
           * in bl_order of the last bit length code to send.
           */
          max_blindex = build_bl_tree(s);
    
          /* Determine the best encoding. Compute the block lengths in bytes. */
          opt_lenb = (s.opt_len + 3 + 7) >>> 3;
          static_lenb = (s.static_len + 3 + 7) >>> 3;
    
          // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
          //        opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
          //        s->sym_next / 3));
    
          if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
    
        } else {
          // Assert(buf != (char*)0, "lost buf");
          opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
        }
    
        if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
          /* 4: two words for the lengths */
    
          /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
           * Otherwise we can't have processed more than WSIZE input bytes since
           * the last block flush, because compression would have been
           * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
           * transform a block into a stored block.
           */
          _tr_stored_block$1(s, buf, stored_len, last);
    
        } else if (s.strategy === Z_FIXED$1 || static_lenb === opt_lenb) {
    
          send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
          compress_block(s, static_ltree, static_dtree);
    
        } else {
          send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
          send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
          compress_block(s, s.dyn_ltree, s.dyn_dtree);
        }
        // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
        /* The above check is made mod 2^32, for files larger than 512 MB
         * and uLong implemented on 32 bits.
         */
        init_block(s);
    
        if (last) {
          bi_windup(s);
        }
        // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
        //       s->compressed_len-7*last));
      };
    
      /* ===========================================================================
       * Save the match info and tally the frequency counts. Return true if
       * the current block must be flushed.
       */
      const _tr_tally$1 = (s, dist, lc) => {
      //    deflate_state *s;
      //    unsigned dist;  /* distance of matched string */
      //    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
    
        s.pending_buf[s.sym_buf + s.sym_next++] = dist;
        s.pending_buf[s.sym_buf + s.sym_next++] = dist >> 8;
        s.pending_buf[s.sym_buf + s.sym_next++] = lc;
        if (dist === 0) {
          /* lc is the unmatched char */
          s.dyn_ltree[lc * 2]/*.Freq*/++;
        } else {
          s.matches++;
          /* Here, lc is the match length - MIN_MATCH */
          dist--;             /* dist = match distance - 1 */
          //Assert((ush)dist < (ush)MAX_DIST(s) &&
          //       (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
          //       (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
    
          s.dyn_ltree[(_length_code[lc] + LITERALS$1 + 1) * 2]/*.Freq*/++;
          s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
        }
    
        return (s.sym_next === s.sym_end);
      };
    
      var _tr_init_1  = _tr_init$1;
      var _tr_stored_block_1 = _tr_stored_block$1;
      var _tr_flush_block_1  = _tr_flush_block$1;
      var _tr_tally_1 = _tr_tally$1;
      var _tr_align_1 = _tr_align$1;
    
      var trees = {
          _tr_init: _tr_init_1,
          _tr_stored_block: _tr_stored_block_1,
          _tr_flush_block: _tr_flush_block_1,
          _tr_tally: _tr_tally_1,
          _tr_align: _tr_align_1
      };
    
      // Note: adler32 takes 12% for level 0 and 2% for level 6.
      // It isn't worth it to make additional optimizations as in original.
      // Small size is preferable.
    
      // (C) 1995-2013 Jean-loup Gailly and Mark Adler
      // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
      //
      // This software is provided 'as-is', without any express or implied
      // warranty. In no event will the authors be held liable for any damages
      // arising from the use of this software.
      //
      // Permission is granted to anyone to use this software for any purpose,
      // including commercial applications, and to alter it and redistribute it
      // freely, subject to the following restrictions:
      //
      // 1. The origin of this software must not be misrepresented; you must not
      //   claim that you wrote the original software. If you use this software
      //   in a product, an acknowledgment in the product documentation would be
      //   appreciated but is not required.
      // 2. Altered source versions must be plainly marked as such, and must not be
      //   misrepresented as being the original software.
      // 3. This notice may not be removed or altered from any source distribution.
    
      const adler32 = (adler, buf, len, pos) => {
        let s1 = (adler & 0xffff) |0,
            s2 = ((adler >>> 16) & 0xffff) |0,
            n = 0;
    
        while (len !== 0) {
          // Set limit ~ twice less than 5552, to keep
          // s2 in 31-bits, because we force signed ints.
          // in other case %= will fail.
          n = len > 2000 ? 2000 : len;
          len -= n;
    
          do {
            s1 = (s1 + buf[pos++]) |0;
            s2 = (s2 + s1) |0;
          } while (--n);
    
          s1 %= 65521;
          s2 %= 65521;
        }
    
        return (s1 | (s2 << 16)) |0;
      };
    
    
      var adler32_1 = adler32;
    
      // Note: we can't get significant speed boost here.
      // So write code to minimize size - no pregenerated tables
      // and array tools dependencies.
    
      // (C) 1995-2013 Jean-loup Gailly and Mark Adler
      // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
      //
      // This software is provided 'as-is', without any express or implied
      // warranty. In no event will the authors be held liable for any damages
      // arising from the use of this software.
      //
      // Permission is granted to anyone to use this software for any purpose,
      // including commercial applications, and to alter it and redistribute it
      // freely, subject to the following restrictions:
      //
      // 1. The origin of this software must not be misrepresented; you must not
      //   claim that you wrote the original software. If you use this software
      //   in a product, an acknowledgment in the product documentation would be
      //   appreciated but is not required.
      // 2. Altered source versions must be plainly marked as such, and must not be
      //   misrepresented as being the original software.
      // 3. This notice may not be removed or altered from any source distribution.
    
      // Use ordinary array, since untyped makes no boost here
      const makeTable = () => {
        let c, table = [];
    
        for (var n = 0; n < 256; n++) {
          c = n;
          for (var k = 0; k < 8; k++) {
            c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
          }
          table[n] = c;
        }
    
        return table;
      };
    
      // Create table on load. Just 255 signed longs. Not a problem.
      const crcTable = new Uint32Array(makeTable());
    
    
      const crc32 = (crc, buf, len, pos) => {
        const t = crcTable;
        const end = pos + len;
    
        crc ^= -1;
    
        for (let i = pos; i < end; i++) {
          crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
        }
    
        return (crc ^ (-1)); // >>> 0;
      };
    
    
      var crc32_1 = crc32;
    
      // (C) 1995-2013 Jean-loup Gailly and Mark Adler
      // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
      //
      // This software is provided 'as-is', without any express or implied
      // warranty. In no event will the authors be held liable for any damages
      // arising from the use of this software.
      //
      // Permission is granted to anyone to use this software for any purpose,
      // including commercial applications, and to alter it and redistribute it
      // freely, subject to the following restrictions:
      //
      // 1. The origin of this software must not be misrepresented; you must not
      //   claim that you wrote the original software. If you use this software
      //   in a product, an acknowledgment in the product documentation would be
      //   appreciated but is not required.
      // 2. Altered source versions must be plainly marked as such, and must not be
      //   misrepresented as being the original software.
      // 3. This notice may not be removed or altered from any source distribution.
    
      var messages = {
        2:      'need dictionary',     /* Z_NEED_DICT       2  */
        1:      'stream end',          /* Z_STREAM_END      1  */
        0:      '',                    /* Z_OK              0  */
        '-1':   'file error',          /* Z_ERRNO         (-1) */
        '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */
        '-3':   'data error',          /* Z_DATA_ERROR    (-3) */
        '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */
        '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */
        '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */
      };
    
      // (C) 1995-2013 Jean-loup Gailly and Mark Adler
      // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
      //
      // This software is provided 'as-is', without any express or implied
      // warranty. In no event will the authors be held liable for any damages
      // arising from the use of this software.
      //
      // Permission is granted to anyone to use this software for any purpose,
      // including commercial applications, and to alter it and redistribute it
      // freely, subject to the following restrictions:
      //
      // 1. The origin of this software must not be misrepresented; you must not
      //   claim that you wrote the original software. If you use this software
      //   in a product, an acknowledgment in the product documentation would be
      //   appreciated but is not required.
      // 2. Altered source versions must be plainly marked as such, and must not be
      //   misrepresented as being the original software.
      // 3. This notice may not be removed or altered from any source distribution.
    
      var constants$2 = {
    
        /* Allowed flush values; see deflate() and inflate() below for details */
        Z_NO_FLUSH:         0,
        Z_PARTIAL_FLUSH:    1,
        Z_SYNC_FLUSH:       2,
        Z_FULL_FLUSH:       3,
        Z_FINISH:           4,
        Z_BLOCK:            5,
        Z_TREES:            6,
    
        /* Return codes for the compression/decompression functions. Negative values
        * are errors, positive values are used for special but normal events.
        */
        Z_OK:               0,
        Z_STREAM_END:       1,
        Z_NEED_DICT:        2,
        Z_ERRNO:           -1,
        Z_STREAM_ERROR:    -2,
        Z_DATA_ERROR:      -3,
        Z_MEM_ERROR:       -4,
        Z_BUF_ERROR:       -5,
        //Z_VERSION_ERROR: -6,
    
        /* compression levels */
        Z_NO_COMPRESSION:         0,
        Z_BEST_SPEED:             1,
        Z_BEST_COMPRESSION:       9,
        Z_DEFAULT_COMPRESSION:   -1,
    
    
        Z_FILTERED:               1,
        Z_HUFFMAN_ONLY:           2,
        Z_RLE:                    3,
        Z_FIXED:                  4,
        Z_DEFAULT_STRATEGY:       0,
    
        /* Possible values of the data_type field (though see inflate()) */
        Z_BINARY:                 0,
        Z_TEXT:                   1,
        //Z_ASCII:                1, // = Z_TEXT (deprecated)
        Z_UNKNOWN:                2,
    
        /* The deflate compression method */
        Z_DEFLATED:               8
        //Z_NULL:                 null // Use -1 or null inline, depending on var type
      };
    
      // (C) 1995-2013 Jean-loup Gailly and Mark Adler
      // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
      //
      // This software is provided 'as-is', without any express or implied
      // warranty. In no event will the authors be held liable for any damages
      // arising from the use of this software.
      //
      // Permission is granted to anyone to use this software for any purpose,
      // including commercial applications, and to alter it and redistribute it
      // freely, subject to the following restrictions:
      //
      // 1. The origin of this software must not be misrepresented; you must not
      //   claim that you wrote the original software. If you use this software
      //   in a product, an acknowledgment in the product documentation would be
      //   appreciated but is not required.
      // 2. Altered source versions must be plainly marked as such, and must not be
      //   misrepresented as being the original software.
      // 3. This notice may not be removed or altered from any source distribution.
    
      const { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align } = trees;
    
    
    
    
      /* Public constants ==========================================================*/
      /* ===========================================================================*/
    
      const {
        Z_NO_FLUSH: Z_NO_FLUSH$2, Z_PARTIAL_FLUSH, Z_FULL_FLUSH: Z_FULL_FLUSH$1, Z_FINISH: Z_FINISH$3, Z_BLOCK: Z_BLOCK$1,
        Z_OK: Z_OK$3, Z_STREAM_END: Z_STREAM_END$3, Z_STREAM_ERROR: Z_STREAM_ERROR$2, Z_DATA_ERROR: Z_DATA_ERROR$2, Z_BUF_ERROR: Z_BUF_ERROR$1,
        Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1,
        Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1,
        Z_UNKNOWN,
        Z_DEFLATED: Z_DEFLATED$2
      } = constants$2;
    
      /*============================================================================*/
    
    
      const MAX_MEM_LEVEL = 9;
      /* Maximum value for memLevel in deflateInit2 */
      const MAX_WBITS$1 = 15;
      /* 32K LZ77 window */
      const DEF_MEM_LEVEL = 8;
    
    
      const LENGTH_CODES  = 29;
      /* number of length codes, not counting the special END_BLOCK code */
      const LITERALS      = 256;
      /* number of literal bytes 0..255 */
      const L_CODES       = LITERALS + 1 + LENGTH_CODES;
      /* number of Literal or Length codes, including the END_BLOCK code */
      const D_CODES       = 30;
      /* number of distance codes */
      const BL_CODES      = 19;
      /* number of codes used to transfer the bit lengths */
      const HEAP_SIZE     = 2 * L_CODES + 1;
      /* maximum heap size */
      const MAX_BITS  = 15;
      /* All codes must not exceed MAX_BITS bits */
    
      const MIN_MATCH = 3;
      const MAX_MATCH = 258;
      const MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
    
      const PRESET_DICT = 0x20;
    
      const INIT_STATE    =  42;    /* zlib header -> BUSY_STATE */
      //#ifdef GZIP
      const GZIP_STATE    =  57;    /* gzip header -> BUSY_STATE | EXTRA_STATE */
      //#endif
      const EXTRA_STATE   =  69;    /* gzip extra block -> NAME_STATE */
      const NAME_STATE    =  73;    /* gzip file name -> COMMENT_STATE */
      const COMMENT_STATE =  91;    /* gzip comment -> HCRC_STATE */
      const HCRC_STATE    = 103;    /* gzip header CRC -> BUSY_STATE */
      const BUSY_STATE    = 113;    /* deflate -> FINISH_STATE */
      const FINISH_STATE  = 666;    /* stream complete */
    
      const BS_NEED_MORE      = 1; /* block not completed, need more input or more output */
      const BS_BLOCK_DONE     = 2; /* block flush performed */
      const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
      const BS_FINISH_DONE    = 4; /* finish done, accept no more input or output */
    
      const OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
    
      const err = (strm, errorCode) => {
        strm.msg = messages[errorCode];
        return errorCode;
      };
    
      const rank = (f) => {
        return ((f) * 2) - ((f) > 4 ? 9 : 0);
      };
    
      const zero = (buf) => {
        let len = buf.length; while (--len >= 0) { buf[len] = 0; }
      };
    
      /* ===========================================================================
       * Slide the hash table when sliding the window down (could be avoided with 32
       * bit values at the expense of memory usage). We slide even when level == 0 to
       * keep the hash table consistent if we switch back to level > 0 later.
       */
      const slide_hash = (s) => {
        let n, m;
        let p;
        let wsize = s.w_size;
    
        n = s.hash_size;
        p = n;
        do {
          m = s.head[--p];
          s.head[p] = (m >= wsize ? m - wsize : 0);
        } while (--n);
        n = wsize;
      //#ifndef FASTEST
        p = n;
        do {
          m = s.prev[--p];
          s.prev[p] = (m >= wsize ? m - wsize : 0);
          /* If n is not on any hash chain, prev[n] is garbage but
           * its value will never be used.
           */
        } while (--n);
      //#endif
      };
    
      /* eslint-disable new-cap */
      let HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask;
      // This hash causes less collisions, https://github.com/nodeca/pako/issues/135
      // But breaks binary compatibility
      //let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;
      let HASH = HASH_ZLIB;
    
    
      /* =========================================================================
       * Flush as much pending output as possible. All deflate() output, except for
       * some deflate_stored() output, goes through this function so some
       * applications may wish to modify it to avoid allocating a large
       * strm->next_out buffer and copying into it. (See also read_buf()).
       */
      const flush_pending = (strm) => {
        const s = strm.state;
    
        //_tr_flush_bits(s);
        let len = s.pending;
        if (len > strm.avail_out) {
          len = strm.avail_out;
        }
        if (len === 0) { return; }
    
        strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out);
        strm.next_out  += len;
        s.pending_out  += len;
        strm.total_out += len;
        strm.avail_out -= len;
        s.pending      -= len;
        if (s.pending === 0) {
          s.pending_out = 0;
        }
      };
    
    
      const flush_block_only = (s, last) => {
        _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
        s.block_start = s.strstart;
        flush_pending(s.strm);
      };
    
    
      const put_byte = (s, b) => {
        s.pending_buf[s.pending++] = b;
      };
    
    
      /* =========================================================================
       * Put a short in the pending buffer. The 16-bit value is put in MSB order.
       * IN assertion: the stream state is correct and there is enough room in
       * pending_buf.
       */
      const putShortMSB = (s, b) => {
    
        //  put_byte(s, (Byte)(b >> 8));
      //  put_byte(s, (Byte)(b & 0xff));
        s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
        s.pending_buf[s.pending++] = b & 0xff;
      };
    
    
      /* ===========================================================================
       * Read a new buffer from the current input stream, update the adler32
       * and total number of bytes read.  All deflate() input goes through
       * this function so some applications may wish to modify it to avoid
       * allocating a large strm->input buffer and copying from it.
       * (See also flush_pending()).
       */
      const read_buf = (strm, buf, start, size) => {
    
        let len = strm.avail_in;
    
        if (len > size) { len = size; }
        if (len === 0) { return 0; }
    
        strm.avail_in -= len;
    
        // zmemcpy(buf, strm->next_in, len);
        buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);
        if (strm.state.wrap === 1) {
          strm.adler = adler32_1(strm.adler, buf, len, start);
        }
    
        else if (strm.state.wrap === 2) {
          strm.adler = crc32_1(strm.adler, buf, len, start);
        }
    
        strm.next_in += len;
        strm.total_in += len;
    
        return len;
      };
    
    
      /* ===========================================================================
       * Set match_start to the longest match starting at the given string and
       * return its length. Matches shorter or equal to prev_length are discarded,
       * in which case the result is equal to prev_length and match_start is
       * garbage.
       * IN assertions: cur_match is the head of the hash chain for the current
       *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
       * OUT assertion: the match length is not greater than s->lookahead.
       */
      const longest_match = (s, cur_match) => {
    
        let chain_length = s.max_chain_length;      /* max hash chain length */
        let scan = s.strstart; /* current string */
        let match;                       /* matched string */
        let len;                           /* length of current match */
        let best_len = s.prev_length;              /* best match length so far */
        let nice_match = s.nice_match;             /* stop if match long enough */
        const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
            s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
    
        const _win = s.window; // shortcut
    
        const wmask = s.w_mask;
        const prev  = s.prev;
    
        /* Stop when cur_match becomes <= limit. To simplify the code,
         * we prevent matches with the string of window index 0.
         */
    
        const strend = s.strstart + MAX_MATCH;
        let scan_end1  = _win[scan + best_len - 1];
        let scan_end   = _win[scan + best_len];
    
        /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
         * It is easy to get rid of this optimization if necessary.
         */
        // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
    
        /* Do not waste too much time if we already have a good match: */
        if (s.prev_length >= s.good_match) {
          chain_length >>= 2;
        }
        /* Do not look for matches beyond the end of the input. This is necessary
         * to make deflate deterministic.
         */
        if (nice_match > s.lookahead) { nice_match = s.lookahead; }
    
        // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
    
        do {
          // Assert(cur_match < s->strstart, "no future");
          match = cur_match;
    
          /* Skip to next match if the match length cannot increase
           * or if the match length is less than 2.  Note that the checks below
           * for insufficient lookahead only occur occasionally for performance
           * reasons.  Therefore uninitialized memory will be accessed, and
           * conditional jumps will be made that depend on those values.
           * However the length of the match is limited to the lookahead, so
           * the output of deflate is not affected by the uninitialized values.
           */
    
          if (_win[match + best_len]     !== scan_end  ||
              _win[match + best_len - 1] !== scan_end1 ||
              _win[match]                !== _win[scan] ||
              _win[++match]              !== _win[scan + 1]) {
            continue;
          }
    
          /* The check at best_len-1 can be removed because it will be made
           * again later. (This heuristic is not always a win.)
           * It is not necessary to compare scan[2] and match[2] since they
           * are always equal when the other bytes match, given that
           * the hash keys are equal and that HASH_BITS >= 8.
           */
          scan += 2;
          match++;
          // Assert(*scan == *match, "match[2]?");
    
          /* We check for insufficient lookahead only every 8th comparison;
           * the 256th check will be made at strstart+258.
           */
          do {
            /*jshint noempty:false*/
          } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
                   _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
                   _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
                   _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
                   scan < strend);
    
          // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
    
          len = MAX_MATCH - (strend - scan);
          scan = strend - MAX_MATCH;
    
          if (len > best_len) {
            s.match_start = cur_match;
            best_len = len;
            if (len >= nice_match) {
              break;
            }
            scan_end1  = _win[scan + best_len - 1];
            scan_end   = _win[scan + best_len];
          }
        } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
    
        if (best_len <= s.lookahead) {
          return best_len;
        }
        return s.lookahead;
      };
    
    
      /* ===========================================================================
       * Fill the window when the lookahead becomes insufficient.
       * Updates strstart and lookahead.
       *
       * IN assertion: lookahead < MIN_LOOKAHEAD
       * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
       *    At least one byte has been read, or avail_in == 0; reads are
       *    performed for at least two bytes (required for the zip translate_eol
       *    option -- not supported here).
       */
      const fill_window = (s) => {
    
        const _w_size = s.w_size;
        let n, more, str;
    
        //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
    
        do {
          more = s.window_size - s.lookahead - s.strstart;
    
          // JS ints have 32 bit, block below not needed
          /* Deal with !@#$% 64K limit: */
          //if (sizeof(int) <= 2) {
          //    if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
          //        more = wsize;
          //
          //  } else if (more == (unsigned)(-1)) {
          //        /* Very unlikely, but possible on 16 bit machine if
          //         * strstart == 0 && lookahead == 1 (input done a byte at time)
          //         */
          //        more--;
          //    }
          //}
    
    
          /* If the window is almost full and there is insufficient lookahead,
           * move the upper half to the lower one to make room in the upper half.
           */
          if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
    
            s.window.set(s.window.subarray(_w_size, _w_size + _w_size - more), 0);
            s.match_start -= _w_size;
            s.strstart -= _w_size;
            /* we now have strstart >= MAX_DIST */
            s.block_start -= _w_size;
            if (s.insert > s.strstart) {
              s.insert = s.strstart;
            }
            slide_hash(s);
            more += _w_size;
          }
          if (s.strm.avail_in === 0) {
            break;
          }
    
          /* If there was no sliding:
           *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
           *    more == window_size - lookahead - strstart
           * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
           * => more >= window_size - 2*WSIZE + 2
           * In the BIG_MEM or MMAP case (not yet supported),
           *   window_size == input_size + MIN_LOOKAHEAD  &&
           *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
           * Otherwise, window_size == 2*WSIZE so more >= 2.
           * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
           */
          //Assert(more >= 2, "more < 2");
          n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
          s.lookahead += n;
    
          /* Initialize the hash value now that we have some input: */
          if (s.lookahead + s.insert >= MIN_MATCH) {
            str = s.strstart - s.insert;
            s.ins_h = s.window[str];
    
            /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
            s.ins_h = HASH(s, s.ins_h, s.window[str + 1]);
      //#if MIN_MATCH != 3
      //        Call update_hash() MIN_MATCH-3 more times
      //#endif
            while (s.insert) {
              /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
              s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);
    
              s.prev[str & s.w_mask] = s.head[s.ins_h];
              s.head[s.ins_h] = str;
              str++;
              s.insert--;
              if (s.lookahead + s.insert < MIN_MATCH) {
                break;
              }
            }
          }
          /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
           * but this is not important since only literal bytes will be emitted.
           */
    
        } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
    
        /* If the WIN_INIT bytes after the end of the current data have never been
         * written, then zero those bytes in order to avoid memory check reports of
         * the use of uninitialized (or uninitialised as Julian writes) bytes by
         * the longest match routines.  Update the high water mark for the next
         * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
         * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
         */
      //  if (s.high_water < s.window_size) {
      //    const curr = s.strstart + s.lookahead;
      //    let init = 0;
      //
      //    if (s.high_water < curr) {
      //      /* Previous high water mark below current data -- zero WIN_INIT
      //       * bytes or up to end of window, whichever is less.
      //       */
      //      init = s.window_size - curr;
      //      if (init > WIN_INIT)
      //        init = WIN_INIT;
      //      zmemzero(s->window + curr, (unsigned)init);
      //      s->high_water = curr + init;
      //    }
      //    else if (s->high_water < (ulg)curr + WIN_INIT) {
      //      /* High water mark at or above current data, but below current data
      //       * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
      //       * to end of window, whichever is less.
      //       */
      //      init = (ulg)curr + WIN_INIT - s->high_water;
      //      if (init > s->window_size - s->high_water)
      //        init = s->window_size - s->high_water;
      //      zmemzero(s->window + s->high_water, (unsigned)init);
      //      s->high_water += init;
      //    }
      //  }
      //
      //  Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
      //    "not enough room for search");
      };
    
      /* ===========================================================================
       * Copy without compression as much as possible from the input stream, return
       * the current block state.
       *
       * In case deflateParams() is used to later switch to a non-zero compression
       * level, s->matches (otherwise unused when storing) keeps track of the number
       * of hash table slides to perform. If s->matches is 1, then one hash table
       * slide will be done when switching. If s->matches is 2, the maximum value
       * allowed here, then the hash table will be cleared, since two or more slides
       * is the same as a clear.
       *
       * deflate_stored() is written to minimize the number of times an input byte is
       * copied. It is most efficient with large input and output buffers, which
       * maximizes the opportunites to have a single copy from next_in to next_out.
       */
      const deflate_stored = (s, flush) => {
    
        /* Smallest worthy block size when not flushing or finishing. By default
         * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
         * large input and output buffers, the stored block size will be larger.
         */
        let min_block = s.pending_buf_size - 5 > s.w_size ? s.w_size : s.pending_buf_size - 5;
    
        /* Copy as many min_block or larger stored blocks directly to next_out as
         * possible. If flushing, copy the remaining available input to next_out as
         * stored blocks, if there is enough space.
         */
        let len, left, have, last = 0;
        let used = s.strm.avail_in;
        do {
          /* Set len to the maximum size block that we can copy directly with the
           * available input data and output space. Set left to how much of that
           * would be copied from what's left in the window.
           */
          len = 65535/* MAX_STORED */;     /* maximum deflate stored block length */
          have = (s.bi_valid + 42) >> 3;     /* number of header bytes */
          if (s.strm.avail_out < have) {         /* need room for header */
            break;
          }
            /* maximum stored block length that will fit in avail_out: */
          have = s.strm.avail_out - have;
          left = s.strstart - s.block_start;  /* bytes left in window */
          if (len > left + s.strm.avail_in) {
            len = left + s.strm.avail_in;   /* limit len to the input */
          }
          if (len > have) {
            len = have;             /* limit len to the output */
          }
    
          /* If the stored block would be less than min_block in length, or if
           * unable to copy all of the available input when flushing, then try
           * copying to the window and the pending buffer instead. Also don't
           * write an empty block when flushing -- deflate() does that.
           */
          if (len < min_block && ((len === 0 && flush !== Z_FINISH$3) ||
                              flush === Z_NO_FLUSH$2 ||
                              len !== left + s.strm.avail_in)) {
            break;
          }
    
          /* Make a dummy stored block in pending to get the header bytes,
           * including any pending bits. This also updates the debugging counts.
           */
          last = flush === Z_FINISH$3 && len === left + s.strm.avail_in ? 1 : 0;
          _tr_stored_block(s, 0, 0, last);
    
          /* Replace the lengths in the dummy stored block with len. */
          s.pending_buf[s.pending - 4] = len;
          s.pending_buf[s.pending - 3] = len >> 8;
          s.pending_buf[s.pending - 2] = ~len;
          s.pending_buf[s.pending - 1] = ~len >> 8;
    
          /* Write the stored block header bytes. */
          flush_pending(s.strm);
    
      //#ifdef ZLIB_DEBUG
      //    /* Update debugging counts for the data about to be copied. */
      //    s->compressed_len += len << 3;
      //    s->bits_sent += len << 3;
      //#endif
    
          /* Copy uncompressed bytes from the window to next_out. */
          if (left) {
            if (left > len) {
              left = len;
            }
            //zmemcpy(s->strm->next_out, s->window + s->block_start, left);
            s.strm.output.set(s.window.subarray(s.block_start, s.block_start + left), s.strm.next_out);
            s.strm.next_out += left;
            s.strm.avail_out -= left;
            s.strm.total_out += left;
            s.block_start += left;
            len -= left;
          }
    
          /* Copy uncompressed bytes directly from next_in to next_out, updating
           * the check value.
           */
          if (len) {
            read_buf(s.strm, s.strm.output, s.strm.next_out, len);
            s.strm.next_out += len;
            s.strm.avail_out -= len;
            s.strm.total_out += len;
          }
        } while (last === 0);
    
        /* Update the sliding window with the last s->w_size bytes of the copied
         * data, or append all of the copied data to the existing window if less
         * than s->w_size bytes were copied. Also update the number of bytes to
         * insert in the hash tables, in the event that deflateParams() switches to
         * a non-zero compression level.
         */
        used -= s.strm.avail_in;    /* number of input bytes directly copied */
        if (used) {
          /* If any input was used, then no unused input remains in the window,
           * therefore s->block_start == s->strstart.
           */
          if (used >= s.w_size) {  /* supplant the previous history */
            s.matches = 2;     /* clear hash */
            //zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);
            s.window.set(s.strm.input.subarray(s.strm.next_in - s.w_size, s.strm.next_in), 0);
            s.strstart = s.w_size;
            s.insert = s.strstart;
          }
          else {
            if (s.window_size - s.strstart <= used) {
              /* Slide the window down. */
              s.strstart -= s.w_size;
              //zmemcpy(s->window, s->window + s->w_size, s->strstart);
              s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);
              if (s.matches < 2) {
                s.matches++;   /* add a pending slide_hash() */
              }
              if (s.insert > s.strstart) {
                s.insert = s.strstart;
              }
            }
            //zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);
            s.window.set(s.strm.input.subarray(s.strm.next_in - used, s.strm.next_in), s.strstart);
            s.strstart += used;
            s.insert += used > s.w_size - s.insert ? s.w_size - s.insert : used;
          }
          s.block_start = s.strstart;
        }
        if (s.high_water < s.strstart) {
          s.high_water = s.strstart;
        }
    
        /* If the last block was written to next_out, then done. */
        if (last) {
          return BS_FINISH_DONE;
        }
    
        /* If flushing and all input has been consumed, then done. */
        if (flush !== Z_NO_FLUSH$2 && flush !== Z_FINISH$3 &&
          s.strm.avail_in === 0 && s.strstart === s.block_start) {
          return BS_BLOCK_DONE;
        }
    
        /* Fill the window with any remaining input. */
        have = s.window_size - s.strstart;
        if (s.strm.avail_in > have && s.block_start >= s.w_size) {
          /* Slide the window down. */
          s.block_start -= s.w_size;
          s.strstart -= s.w_size;
          //zmemcpy(s->window, s->window + s->w_size, s->strstart);
          s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);
          if (s.matches < 2) {
            s.matches++;       /* add a pending slide_hash() */
          }
          have += s.w_size;      /* more space now */
          if (s.insert > s.strstart) {
            s.insert = s.strstart;
          }
        }
        if (have > s.strm.avail_in) {
          have = s.strm.avail_in;
        }
        if (have) {
          read_buf(s.strm, s.window, s.strstart, have);
          s.strstart += have;
          s.insert += have > s.w_size - s.insert ? s.w_size - s.insert : have;
        }
        if (s.high_water < s.strstart) {
          s.high_water = s.strstart;
        }
    
        /* There was not enough avail_out to write a complete worthy or flushed
         * stored block to next_out. Write a stored block to pending instead, if we
         * have enough input for a worthy block, or if flushing and there is enough
         * room for the remaining input as a stored block in the pending buffer.
         */
        have = (s.bi_valid + 42) >> 3;     /* number of header bytes */
          /* maximum stored block length that will fit in pending: */
        have = s.pending_buf_size - have > 65535/* MAX_STORED */ ? 65535/* MAX_STORED */ : s.pending_buf_size - have;
        min_block = have > s.w_size ? s.w_size : have;
        left = s.strstart - s.block_start;
        if (left >= min_block ||
           ((left || flush === Z_FINISH$3) && flush !== Z_NO_FLUSH$2 &&
           s.strm.avail_in === 0 && left <= have)) {
          len = left > have ? have : left;
          last = flush === Z_FINISH$3 && s.strm.avail_in === 0 &&
               len === left ? 1 : 0;
          _tr_stored_block(s, s.block_start, len, last);
          s.block_start += len;
          flush_pending(s.strm);
        }
    
        /* We've done all we can with the available input and output. */
        return last ? BS_FINISH_STARTED : BS_NEED_MORE;
      };
    
    
      /* ===========================================================================
       * Compress as much as possible from the input stream, return the current
       * block state.
       * This function does not perform lazy evaluation of matches and inserts
       * new strings in the dictionary only for unmatched strings or for short
       * matches. It is used only for the fast compression options.
       */
      const deflate_fast = (s, flush) => {
    
        let hash_head;        /* head of the hash chain */
        let bflush;           /* set if current block must be flushed */
    
        for (;;) {
          /* Make sure that we always have enough lookahead, except
           * at the end of the input file. We need MAX_MATCH bytes
           * for the next match, plus MIN_MATCH bytes to insert the
           * string following the next match.
           */
          if (s.lookahead < MIN_LOOKAHEAD) {
            fill_window(s);
            if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {
              return BS_NEED_MORE;
            }
            if (s.lookahead === 0) {
              break; /* flush the current block */
            }
          }
    
          /* Insert the string window[strstart .. strstart+2] in the
           * dictionary, and set hash_head to the head of the hash chain:
           */
          hash_head = 0/*NIL*/;
          if (s.lookahead >= MIN_MATCH) {
            /*** INSERT_STRING(s, s.strstart, hash_head); ***/
            s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
            hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
            s.head[s.ins_h] = s.strstart;
            /***/
          }
    
          /* Find the longest match, discarding those <= prev_length.
           * At this point we have always match_length < MIN_MATCH
           */
          if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
            /* To simplify the code, we prevent matches with the string
             * of window index 0 (in particular we have to avoid a match
             * of the string with itself at the start of the input file).
             */
            s.match_length = longest_match(s, hash_head);
            /* longest_match() sets match_start */
          }
          if (s.match_length >= MIN_MATCH) {
            // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
    
            /*** _tr_tally_dist(s, s.strstart - s.match_start,
                           s.match_length - MIN_MATCH, bflush); ***/
            bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
    
            s.lookahead -= s.match_length;
    
            /* Insert new strings in the hash table only if the match length
             * is not too large. This saves time but degrades compression.
             */
            if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
              s.match_length--; /* string at strstart already in table */
              do {
                s.strstart++;
                /*** INSERT_STRING(s, s.strstart, hash_head); ***/
                s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
                hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
                s.head[s.ins_h] = s.strstart;
                /***/
                /* strstart never exceeds WSIZE-MAX_MATCH, so there are
                 * always MIN_MATCH bytes ahead.
                 */
              } while (--s.match_length !== 0);
              s.strstart++;
            } else
            {
              s.strstart += s.match_length;
              s.match_length = 0;
              s.ins_h = s.window[s.strstart];
              /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
              s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]);
    
      //#if MIN_MATCH != 3
      //                Call UPDATE_HASH() MIN_MATCH-3 more times
      //#endif
              /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
               * matter since it will be recomputed at next deflate call.
               */
            }
          } else {
            /* No match, output a literal byte */
            //Tracevv((stderr,"%c", s.window[s.strstart]));
            /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
            bflush = _tr_tally(s, 0, s.window[s.strstart]);
    
            s.lookahead--;
            s.strstart++;
          }
          if (bflush) {
            /*** FLUSH_BLOCK(s, 0); ***/
            flush_block_only(s, false);
            if (s.strm.avail_out === 0) {
              return BS_NEED_MORE;
            }
            /***/
          }
        }
        s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
        if (flush === Z_FINISH$3) {
          /*** FLUSH_BLOCK(s, 1); ***/
          flush_block_only(s, true);
          if (s.strm.avail_out === 0) {
            return BS_FINISH_STARTED;
          }
          /***/
          return BS_FINISH_DONE;
        }
        if (s.sym_next) {
          /*** FLUSH_BLOCK(s, 0); ***/
          flush_block_only(s, false);
          if (s.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
          /***/
        }
        return BS_BLOCK_DONE;
      };
    
      /* ===========================================================================
       * Same as above, but achieves better compression. We use a lazy
       * evaluation for matches: a match is finally adopted only if there is
       * no better match at the next window position.
       */
      const deflate_slow = (s, flush) => {
    
        let hash_head;          /* head of hash chain */
        let bflush;              /* set if current block must be flushed */
    
        let max_insert;
    
        /* Process the input block. */
        for (;;) {
          /* Make sure that we always have enough lookahead, except
           * at the end of the input file. We need MAX_MATCH bytes
           * for the next match, plus MIN_MATCH bytes to insert the
           * string following the next match.
           */
          if (s.lookahead < MIN_LOOKAHEAD) {
            fill_window(s);
            if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {
              return BS_NEED_MORE;
            }
            if (s.lookahead === 0) { break; } /* flush the current block */
          }
    
          /* Insert the string window[strstart .. strstart+2] in the
           * dictionary, and set hash_head to the head of the hash chain:
           */
          hash_head = 0/*NIL*/;
          if (s.lookahead >= MIN_MATCH) {
            /*** INSERT_STRING(s, s.strstart, hash_head); ***/
            s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
            hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
            s.head[s.ins_h] = s.strstart;
            /***/
          }
    
          /* Find the longest match, discarding those <= prev_length.
           */
          s.prev_length = s.match_length;
          s.prev_match = s.match_start;
          s.match_length = MIN_MATCH - 1;
    
          if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
              s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
            /* To simplify the code, we prevent matches with the string
             * of window index 0 (in particular we have to avoid a match
             * of the string with itself at the start of the input file).
             */
            s.match_length = longest_match(s, hash_head);
            /* longest_match() sets match_start */
    
            if (s.match_length <= 5 &&
               (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
    
              /* If prev_match is also MIN_MATCH, match_start is garbage
               * but we will ignore the current match anyway.
               */
              s.match_length = MIN_MATCH - 1;
            }
          }
          /* If there was a match at the previous step and the current
           * match is not better, output the previous match:
           */
          if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
            max_insert = s.strstart + s.lookahead - MIN_MATCH;
            /* Do not insert strings in hash table beyond this. */
    
            //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
    
            /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
                           s.prev_length - MIN_MATCH, bflush);***/
            bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
            /* Insert in hash table all strings up to the end of the match.
             * strstart-1 and strstart are already inserted. If there is not
             * enough lookahead, the last two strings are not inserted in
             * the hash table.
             */
            s.lookahead -= s.prev_length - 1;
            s.prev_length -= 2;
            do {
              if (++s.strstart <= max_insert) {
                /*** INSERT_STRING(s, s.strstart, hash_head); ***/
                s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
                hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
                s.head[s.ins_h] = s.strstart;
                /***/
              }
            } while (--s.prev_length !== 0);
            s.match_available = 0;
            s.match_length = MIN_MATCH - 1;
            s.strstart++;
    
            if (bflush) {
              /*** FLUSH_BLOCK(s, 0); ***/
              flush_block_only(s, false);
              if (s.strm.avail_out === 0) {
                return BS_NEED_MORE;
              }
              /***/
            }
    
          } else if (s.match_available) {
            /* If there was no match at the previous position, output a
             * single literal. If there was a match but the current match
             * is longer, truncate the previous match to a single literal.
             */
            //Tracevv((stderr,"%c", s->window[s->strstart-1]));
            /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
            bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
    
            if (bflush) {
              /*** FLUSH_BLOCK_ONLY(s, 0) ***/
              flush_block_only(s, false);
              /***/
            }
            s.strstart++;
            s.lookahead--;
            if (s.strm.avail_out === 0) {
              return BS_NEED_MORE;
            }
          } else {
            /* There is no previous match to compare with, wait for
             * the next step to decide.
             */
            s.match_available = 1;
            s.strstart++;
            s.lookahead--;
          }
        }
        //Assert (flush != Z_NO_FLUSH, "no flush?");
        if (s.match_available) {
          //Tracevv((stderr,"%c", s->window[s->strstart-1]));
          /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
          bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
    
          s.match_available = 0;
        }
        s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
        if (flush === Z_FINISH$3) {
          /*** FLUSH_BLOCK(s, 1); ***/
          flush_block_only(s, true);
          if (s.strm.avail_out === 0) {
            return BS_FINISH_STARTED;
          }
          /***/
          return BS_FINISH_DONE;
        }
        if (s.sym_next) {
          /*** FLUSH_BLOCK(s, 0); ***/
          flush_block_only(s, false);
          if (s.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
          /***/
        }
    
        return BS_BLOCK_DONE;
      };
    
    
      /* ===========================================================================
       * For Z_RLE, simply look for runs of bytes, generate matches only of distance
       * one.  Do not maintain a hash table.  (It will be regenerated if this run of
       * deflate switches away from Z_RLE.)
       */
      const deflate_rle = (s, flush) => {
    
        let bflush;            /* set if current block must be flushed */
        let prev;              /* byte at distance one to match */
        let scan, strend;      /* scan goes up to strend for length of run */
    
        const _win = s.window;
    
        for (;;) {
          /* Make sure that we always have enough lookahead, except
           * at the end of the input file. We need MAX_MATCH bytes
           * for the longest run, plus one for the unrolled loop.
           */
          if (s.lookahead <= MAX_MATCH) {
            fill_window(s);
            if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH$2) {
              return BS_NEED_MORE;
            }
            if (s.lookahead === 0) { break; } /* flush the current block */
          }
    
          /* See how many times the previous byte repeats */
          s.match_length = 0;
          if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
            scan = s.strstart - 1;
            prev = _win[scan];
            if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
              strend = s.strstart + MAX_MATCH;
              do {
                /*jshint noempty:false*/
              } while (prev === _win[++scan] && prev === _win[++scan] &&
                       prev === _win[++scan] && prev === _win[++scan] &&
                       prev === _win[++scan] && prev === _win[++scan] &&
                       prev === _win[++scan] && prev === _win[++scan] &&
                       scan < strend);
              s.match_length = MAX_MATCH - (strend - scan);
              if (s.match_length > s.lookahead) {
                s.match_length = s.lookahead;
              }
            }
            //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
          }
    
          /* Emit match if have run of MIN_MATCH or longer, else emit literal */
          if (s.match_length >= MIN_MATCH) {
            //check_match(s, s.strstart, s.strstart - 1, s.match_length);
    
            /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
            bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH);
    
            s.lookahead -= s.match_length;
            s.strstart += s.match_length;
            s.match_length = 0;
          } else {
            /* No match, output a literal byte */
            //Tracevv((stderr,"%c", s->window[s->strstart]));
            /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
            bflush = _tr_tally(s, 0, s.window[s.strstart]);
    
            s.lookahead--;
            s.strstart++;
          }
          if (bflush) {
            /*** FLUSH_BLOCK(s, 0); ***/
            flush_block_only(s, false);
            if (s.strm.avail_out === 0) {
              return BS_NEED_MORE;
            }
            /***/
          }
        }
        s.insert = 0;
        if (flush === Z_FINISH$3) {
          /*** FLUSH_BLOCK(s, 1); ***/
          flush_block_only(s, true);
          if (s.strm.avail_out === 0) {
            return BS_FINISH_STARTED;
          }
          /***/
          return BS_FINISH_DONE;
        }
        if (s.sym_next) {
          /*** FLUSH_BLOCK(s, 0); ***/
          flush_block_only(s, false);
          if (s.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
          /***/
        }
        return BS_BLOCK_DONE;
      };
    
      /* ===========================================================================
       * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
       * (It will be regenerated if this run of deflate switches away from Huffman.)
       */
      const deflate_huff = (s, flush) => {
    
        let bflush;             /* set if current block must be flushed */
    
        for (;;) {
          /* Make sure that we have a literal to write. */
          if (s.lookahead === 0) {
            fill_window(s);
            if (s.lookahead === 0) {
              if (flush === Z_NO_FLUSH$2) {
                return BS_NEED_MORE;
              }
              break;      /* flush the current block */
            }
          }
    
          /* Output a literal byte */
          s.match_length = 0;
          //Tracevv((stderr,"%c", s->window[s->strstart]));
          /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
          bflush = _tr_tally(s, 0, s.window[s.strstart]);
          s.lookahead--;
          s.strstart++;
          if (bflush) {
            /*** FLUSH_BLOCK(s, 0); ***/
            flush_block_only(s, false);
            if (s.strm.avail_out === 0) {
              return BS_NEED_MORE;
            }
            /***/
          }
        }
        s.insert = 0;
        if (flush === Z_FINISH$3) {
          /*** FLUSH_BLOCK(s, 1); ***/
          flush_block_only(s, true);
          if (s.strm.avail_out === 0) {
            return BS_FINISH_STARTED;
          }
          /***/
          return BS_FINISH_DONE;
        }
        if (s.sym_next) {
          /*** FLUSH_BLOCK(s, 0); ***/
          flush_block_only(s, false);
          if (s.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
          /***/
        }
        return BS_BLOCK_DONE;
      };
    
      /* Values for max_lazy_match, good_match and max_chain_length, depending on
       * the desired pack level (0..9). The values given below have been tuned to
       * exclude worst case performance for pathological files. Better values may be
       * found for specific files.
       */
      function Config(good_length, max_lazy, nice_length, max_chain, func) {
    
        this.good_length = good_length;
        this.max_lazy = max_lazy;
        this.nice_length = nice_length;
        this.max_chain = max_chain;
        this.func = func;
      }
    
      const configuration_table = [
        /*      good lazy nice chain */
        new Config(0, 0, 0, 0, deflate_stored),          /* 0 store only */
        new Config(4, 4, 8, 4, deflate_fast),            /* 1 max speed, no lazy matches */
        new Config(4, 5, 16, 8, deflate_fast),           /* 2 */
        new Config(4, 6, 32, 32, deflate_fast),          /* 3 */
    
        new Config(4, 4, 16, 16, deflate_slow),          /* 4 lazy matches */
        new Config(8, 16, 32, 32, deflate_slow),         /* 5 */
        new Config(8, 16, 128, 128, deflate_slow),       /* 6 */
        new Config(8, 32, 128, 256, deflate_slow),       /* 7 */
        new Config(32, 128, 258, 1024, deflate_slow),    /* 8 */
        new Config(32, 258, 258, 4096, deflate_slow)     /* 9 max compression */
      ];
    
    
      /* ===========================================================================
       * Initialize the "longest match" routines for a new zlib stream
       */
      const lm_init = (s) => {
    
        s.window_size = 2 * s.w_size;
    
        /*** CLEAR_HASH(s); ***/
        zero(s.head); // Fill with NIL (= 0);
    
        /* Set the default configuration parameters:
         */
        s.max_lazy_match = configuration_table[s.level].max_lazy;
        s.good_match = configuration_table[s.level].good_length;
        s.nice_match = configuration_table[s.level].nice_length;
        s.max_chain_length = configuration_table[s.level].max_chain;
    
        s.strstart = 0;
        s.block_start = 0;
        s.lookahead = 0;
        s.insert = 0;
        s.match_length = s.prev_length = MIN_MATCH - 1;
        s.match_available = 0;
        s.ins_h = 0;
      };
    
    
      function DeflateState() {
        this.strm = null;            /* pointer back to this zlib stream */
        this.status = 0;            /* as the name implies */
        this.pending_buf = null;      /* output still pending */
        this.pending_buf_size = 0;  /* size of pending_buf */
        this.pending_out = 0;       /* next pending byte to output to the stream */
        this.pending = 0;           /* nb of bytes in the pending buffer */
        this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
        this.gzhead = null;         /* gzip header information to write */
        this.gzindex = 0;           /* where in extra, name, or comment */
        this.method = Z_DEFLATED$2; /* can only be DEFLATED */
        this.last_flush = -1;   /* value of flush param for previous deflate call */
    
        this.w_size = 0;  /* LZ77 window size (32K by default) */
        this.w_bits = 0;  /* log2(w_size)  (8..16) */
        this.w_mask = 0;  /* w_size - 1 */
    
        this.window = null;
        /* Sliding window. Input bytes are read into the second half of the window,
         * and move to the first half later to keep a dictionary of at least wSize
         * bytes. With this organization, matches are limited to a distance of
         * wSize-MAX_MATCH bytes, but this ensures that IO is always
         * performed with a length multiple of the block size.
         */
    
        this.window_size = 0;
        /* Actual size of window: 2*wSize, except when the user input buffer
         * is directly used as sliding window.
         */
    
        this.prev = null;
        /* Link to older string with same hash index. To limit the size of this
         * array to 64K, this link is maintained only for the last 32K strings.
         * An index in this array is thus a window index modulo 32K.
         */
    
        this.head = null;   /* Heads of the hash chains or NIL. */
    
        this.ins_h = 0;       /* hash index of string to be inserted */
        this.hash_size = 0;   /* number of elements in hash table */
        this.hash_bits = 0;   /* log2(hash_size) */
        this.hash_mask = 0;   /* hash_size-1 */
    
        this.hash_shift = 0;
        /* Number of bits by which ins_h must be shifted at each input
         * step. It must be such that after MIN_MATCH steps, the oldest
         * byte no longer takes part in the hash key, that is:
         *   hash_shift * MIN_MATCH >= hash_bits
         */
    
        this.block_start = 0;
        /* Window position at the beginning of the current output block. Gets
         * negative when the window is moved backwards.
         */
    
        this.match_length = 0;      /* length of best match */
        this.prev_match = 0;        /* previous match */
        this.match_available = 0;   /* set if previous match exists */
        this.strstart = 0;          /* start of string to insert */
        this.match_start = 0;       /* start of matching string */
        this.lookahead = 0;         /* number of valid bytes ahead in window */
    
        this.prev_length = 0;
        /* Length of the best match at previous step. Matches not greater than this
         * are discarded. This is used in the lazy match evaluation.
         */
    
        this.max_chain_length = 0;
        /* To speed up deflation, hash chains are never searched beyond this
         * length.  A higher limit improves compression ratio but degrades the
         * speed.
         */
    
        this.max_lazy_match = 0;
        /* Attempt to find a better match only when the current match is strictly
         * smaller than this value. This mechanism is used only for compression
         * levels >= 4.
         */
        // That's alias to max_lazy_match, don't use directly
        //this.max_insert_length = 0;
        /* Insert new strings in the hash table only if the match length is not
         * greater than this length. This saves time but degrades compression.
         * max_insert_length is used only for compression levels <= 3.
         */
    
        this.level = 0;     /* compression level (1..9) */
        this.strategy = 0;  /* favor or force Huffman coding*/
    
        this.good_match = 0;
        /* Use a faster search when the previous match is longer than this */
    
        this.nice_match = 0; /* Stop searching when current match exceeds this */
    
                    /* used by trees.c: */
    
        /* Didn't use ct_data typedef below to suppress compiler warning */
    
        // struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
        // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
        // struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
    
        // Use flat array of DOUBLE size, with interleaved fata,
        // because JS does not support effective
        this.dyn_ltree  = new Uint16Array(HEAP_SIZE * 2);
        this.dyn_dtree  = new Uint16Array((2 * D_CODES + 1) * 2);
        this.bl_tree    = new Uint16Array((2 * BL_CODES + 1) * 2);
        zero(this.dyn_ltree);
        zero(this.dyn_dtree);
        zero(this.bl_tree);
    
        this.l_desc   = null;         /* desc. for literal tree */
        this.d_desc   = null;         /* desc. for distance tree */
        this.bl_desc  = null;         /* desc. for bit length tree */
    
        //ush bl_count[MAX_BITS+1];
        this.bl_count = new Uint16Array(MAX_BITS + 1);
        /* number of codes at each bit length for an optimal tree */
    
        //int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
        this.heap = new Uint16Array(2 * L_CODES + 1);  /* heap used to build the Huffman trees */
        zero(this.heap);
    
        this.heap_len = 0;               /* number of elements in the heap */
        this.heap_max = 0;               /* element of largest frequency */
        /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
         * The same heap array is used to build all trees.
         */
    
        this.depth = new Uint16Array(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
        zero(this.depth);
        /* Depth of each subtree used as tie breaker for trees of equal frequency
         */
    
        this.sym_buf = 0;        /* buffer for distances and literals/lengths */
    
        this.lit_bufsize = 0;
        /* Size of match buffer for literals/lengths.  There are 4 reasons for
         * limiting lit_bufsize to 64K:
         *   - frequencies can be kept in 16 bit counters
         *   - if compression is not successful for the first block, all input
         *     data is still in the window so we can still emit a stored block even
         *     when input comes from standard input.  (This can also be done for
         *     all blocks if lit_bufsize is not greater than 32K.)
         *   - if compression is not successful for a file smaller than 64K, we can
         *     even emit a stored file instead of a stored block (saving 5 bytes).
         *     This is applicable only for zip (not gzip or zlib).
         *   - creating new Huffman trees less frequently may not provide fast
         *     adaptation to changes in the input data statistics. (Take for
         *     example a binary file with poorly compressible code followed by
         *     a highly compressible string table.) Smaller buffer sizes give
         *     fast adaptation but have of course the overhead of transmitting
         *     trees more frequently.
         *   - I can't count above 4
         */
    
        this.sym_next = 0;      /* running index in sym_buf */
        this.sym_end = 0;       /* symbol table full when sym_next reaches this */
    
        this.opt_len = 0;       /* bit length of current block with optimal trees */
        this.static_len = 0;    /* bit length of current block with static trees */
        this.matches = 0;       /* number of string matches in current block */
        this.insert = 0;        /* bytes at end of window left to insert */
    
    
        this.bi_buf = 0;
        /* Output buffer. bits are inserted starting at the bottom (least
         * significant bits).
         */
        this.bi_valid = 0;
        /* Number of valid bits in bi_buf.  All bits above the last valid bit
         * are always zero.
         */
    
        // Used for window memory init. We safely ignore it for JS. That makes
        // sense only for pointers and memory check tools.
        //this.high_water = 0;
        /* High water mark offset in window for initialized bytes -- bytes above
         * this are set to zero in order to avoid memory check warnings when
         * longest match routines access bytes past the input.  This is then
         * updated to the new high water mark.
         */
      }
    
    
      /* =========================================================================
       * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
       */
      const deflateStateCheck = (strm) => {
    
        if (!strm) {
          return 1;
        }
        const s = strm.state;
        if (!s || s.strm !== strm || (s.status !== INIT_STATE &&
      //#ifdef GZIP
                                      s.status !== GZIP_STATE &&
      //#endif
                                      s.status !== EXTRA_STATE &&
                                      s.status !== NAME_STATE &&
                                      s.status !== COMMENT_STATE &&
                                      s.status !== HCRC_STATE &&
                                      s.status !== BUSY_STATE &&
                                      s.status !== FINISH_STATE)) {
          return 1;
        }
        return 0;
      };
    
    
      const deflateResetKeep = (strm) => {
    
        if (deflateStateCheck(strm)) {
          return err(strm, Z_STREAM_ERROR$2);
        }
    
        strm.total_in = strm.total_out = 0;
        strm.data_type = Z_UNKNOWN;
    
        const s = strm.state;
        s.pending = 0;
        s.pending_out = 0;
    
        if (s.wrap < 0) {
          s.wrap = -s.wrap;
          /* was made negative by deflate(..., Z_FINISH); */
        }
        s.status =
      //#ifdef GZIP
          s.wrap === 2 ? GZIP_STATE :
      //#endif
          s.wrap ? INIT_STATE : BUSY_STATE;
        strm.adler = (s.wrap === 2) ?
          0  // crc32(0, Z_NULL, 0)
        :
          1; // adler32(0, Z_NULL, 0)
        s.last_flush = -2;
        _tr_init(s);
        return Z_OK$3;
      };
    
    
      const deflateReset = (strm) => {
    
        const ret = deflateResetKeep(strm);
        if (ret === Z_OK$3) {
          lm_init(strm.state);
        }
        return ret;
      };
    
    
      const deflateSetHeader = (strm, head) => {
    
        if (deflateStateCheck(strm) || strm.state.wrap !== 2) {
          return Z_STREAM_ERROR$2;
        }
        strm.state.gzhead = head;
        return Z_OK$3;
      };
    
    
      const deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {
    
        if (!strm) { // === Z_NULL
          return Z_STREAM_ERROR$2;
        }
        let wrap = 1;
    
        if (level === Z_DEFAULT_COMPRESSION$1) {
          level = 6;
        }
    
        if (windowBits < 0) { /* suppress zlib wrapper */
          wrap = 0;
          windowBits = -windowBits;
        }
    
        else if (windowBits > 15) {
          wrap = 2;           /* write gzip wrapper instead */
          windowBits -= 16;
        }
    
    
        if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED$2 ||
          windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
          strategy < 0 || strategy > Z_FIXED || (windowBits === 8 && wrap !== 1)) {
          return err(strm, Z_STREAM_ERROR$2);
        }
    
    
        if (windowBits === 8) {
          windowBits = 9;
        }
        /* until 256-byte window bug fixed */
    
        const s = new DeflateState();
    
        strm.state = s;
        s.strm = strm;
        s.status = INIT_STATE;     /* to pass state test in deflateReset() */
    
        s.wrap = wrap;
        s.gzhead = null;
        s.w_bits = windowBits;
        s.w_size = 1 << s.w_bits;
        s.w_mask = s.w_size - 1;
    
        s.hash_bits = memLevel + 7;
        s.hash_size = 1 << s.hash_bits;
        s.hash_mask = s.hash_size - 1;
        s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
    
        s.window = new Uint8Array(s.w_size * 2);
        s.head = new Uint16Array(s.hash_size);
        s.prev = new Uint16Array(s.w_size);
    
        // Don't need mem init magic for JS.
        //s.high_water = 0;  /* nothing written to s->window yet */
    
        s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
    
        /* We overlay pending_buf and sym_buf. This works since the average size
         * for length/distance pairs over any compressed block is assured to be 31
         * bits or less.
         *
         * Analysis: The longest fixed codes are a length code of 8 bits plus 5
         * extra bits, for lengths 131 to 257. The longest fixed distance codes are
         * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
         * possible fixed-codes length/distance pair is then 31 bits total.
         *
         * sym_buf starts one-fourth of the way into pending_buf. So there are
         * three bytes in sym_buf for every four bytes in pending_buf. Each symbol
         * in sym_buf is three bytes -- two for the distance and one for the
         * literal/length. As each symbol is consumed, the pointer to the next
         * sym_buf value to read moves forward three bytes. From that symbol, up to
         * 31 bits are written to pending_buf. The closest the written pending_buf
         * bits gets to the next sym_buf symbol to read is just before the last
         * code is written. At that time, 31*(n-2) bits have been written, just
         * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at
         * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1
         * symbols are written.) The closest the writing gets to what is unread is
         * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and
         * can range from 128 to 32768.
         *
         * Therefore, at a minimum, there are 142 bits of space between what is
         * written and what is read in the overlain buffers, so the symbols cannot
         * be overwritten by the compressed data. That space is actually 139 bits,
         * due to the three-bit fixed-code block header.
         *
         * That covers the case where either Z_FIXED is specified, forcing fixed
         * codes, or when the use of fixed codes is chosen, because that choice
         * results in a smaller compressed block than dynamic codes. That latter
         * condition then assures that the above analysis also covers all dynamic
         * blocks. A dynamic-code block will only be chosen to be emitted if it has
         * fewer bits than a fixed-code block would for the same set of symbols.
         * Therefore its average symbol length is assured to be less than 31. So
         * the compressed data for a dynamic block also cannot overwrite the
         * symbols from which it is being constructed.
         */
    
        s.pending_buf_size = s.lit_bufsize * 4;
        s.pending_buf = new Uint8Array(s.pending_buf_size);
    
        // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
        //s->sym_buf = s->pending_buf + s->lit_bufsize;
        s.sym_buf = s.lit_bufsize;
    
        //s->sym_end = (s->lit_bufsize - 1) * 3;
        s.sym_end = (s.lit_bufsize - 1) * 3;
        /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
         * on 16 bit machines and because stored blocks are restricted to
         * 64K-1 bytes.
         */
    
        s.level = level;
        s.strategy = strategy;
        s.method = method;
    
        return deflateReset(strm);
      };
    
      const deflateInit = (strm, level) => {
    
        return deflateInit2(strm, level, Z_DEFLATED$2, MAX_WBITS$1, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY$1);
      };
    
    
      /* ========================================================================= */
      const deflate$2 = (strm, flush) => {
    
        if (deflateStateCheck(strm) || flush > Z_BLOCK$1 || flush < 0) {
          return strm ? err(strm, Z_STREAM_ERROR$2) : Z_STREAM_ERROR$2;
        }
    
        const s = strm.state;
    
        if (!strm.output ||
            (strm.avail_in !== 0 && !strm.input) ||
            (s.status === FINISH_STATE && flush !== Z_FINISH$3)) {
          return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR$1 : Z_STREAM_ERROR$2);
        }
    
        const old_flush = s.last_flush;
        s.last_flush = flush;
    
        /* Flush as much pending output as possible */
        if (s.pending !== 0) {
          flush_pending(strm);
          if (strm.avail_out === 0) {
            /* Since avail_out is 0, deflate will be called again with
             * more output space, but possibly with both pending and
             * avail_in equal to zero. There won't be anything to do,
             * but this is not an error situation so make sure we
             * return OK instead of BUF_ERROR at next call of deflate:
             */
            s.last_flush = -1;
            return Z_OK$3;
          }
    
          /* Make sure there is something to do and avoid duplicate consecutive
           * flushes. For repeated and useless calls with Z_FINISH, we keep
           * returning Z_STREAM_END instead of Z_BUF_ERROR.
           */
        } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
          flush !== Z_FINISH$3) {
          return err(strm, Z_BUF_ERROR$1);
        }
    
        /* User must not provide more input after the first FINISH: */
        if (s.status === FINISH_STATE && strm.avail_in !== 0) {
          return err(strm, Z_BUF_ERROR$1);
        }
    
        /* Write the header */
        if (s.status === INIT_STATE && s.wrap === 0) {
          s.status = BUSY_STATE;
        }
        if (s.status === INIT_STATE) {
          /* zlib header */
          let header = (Z_DEFLATED$2 + ((s.w_bits - 8) << 4)) << 8;
          let level_flags = -1;
    
          if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
            level_flags = 0;
          } else if (s.level < 6) {
            level_flags = 1;
          } else if (s.level === 6) {
            level_flags = 2;
          } else {
            level_flags = 3;
          }
          header |= (level_flags << 6);
          if (s.strstart !== 0) { header |= PRESET_DICT; }
          header += 31 - (header % 31);
    
          putShortMSB(s, header);
    
          /* Save the adler32 of the preset dictionary: */
          if (s.strstart !== 0) {
            putShortMSB(s, strm.adler >>> 16);
            putShortMSB(s, strm.adler & 0xffff);
          }
          strm.adler = 1; // adler32(0L, Z_NULL, 0);
          s.status = BUSY_STATE;
    
          /* Compression must start with an empty pending buffer */
          flush_pending(strm);
          if (s.pending !== 0) {
            s.last_flush = -1;
            return Z_OK$3;
          }
        }
      //#ifdef GZIP
        if (s.status === GZIP_STATE) {
          /* gzip header */
          strm.adler = 0;  //crc32(0L, Z_NULL, 0);
          put_byte(s, 31);
          put_byte(s, 139);
          put_byte(s, 8);
          if (!s.gzhead) { // s->gzhead == Z_NULL
            put_byte(s, 0);
            put_byte(s, 0);
            put_byte(s, 0);
            put_byte(s, 0);
            put_byte(s, 0);
            put_byte(s, s.level === 9 ? 2 :
                        (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
                         4 : 0));
            put_byte(s, OS_CODE);
            s.status = BUSY_STATE;
    
            /* Compression must start with an empty pending buffer */
            flush_pending(strm);
            if (s.pending !== 0) {
              s.last_flush = -1;
              return Z_OK$3;
            }
          }
          else {
            put_byte(s, (s.gzhead.text ? 1 : 0) +
                        (s.gzhead.hcrc ? 2 : 0) +
                        (!s.gzhead.extra ? 0 : 4) +
                        (!s.gzhead.name ? 0 : 8) +
                        (!s.gzhead.comment ? 0 : 16)
            );
            put_byte(s, s.gzhead.time & 0xff);
            put_byte(s, (s.gzhead.time >> 8) & 0xff);
            put_byte(s, (s.gzhead.time >> 16) & 0xff);
            put_byte(s, (s.gzhead.time >> 24) & 0xff);
            put_byte(s, s.level === 9 ? 2 :
                        (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
                         4 : 0));
            put_byte(s, s.gzhead.os & 0xff);
            if (s.gzhead.extra && s.gzhead.extra.length) {
              put_byte(s, s.gzhead.extra.length & 0xff);
              put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
            }
            if (s.gzhead.hcrc) {
              strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0);
            }
            s.gzindex = 0;
            s.status = EXTRA_STATE;
          }
        }
        if (s.status === EXTRA_STATE) {
          if (s.gzhead.extra/* != Z_NULL*/) {
            let beg = s.pending;   /* start of bytes to update crc */
            let left = (s.gzhead.extra.length & 0xffff) - s.gzindex;
            while (s.pending + left > s.pending_buf_size) {
              let copy = s.pending_buf_size - s.pending;
              // zmemcpy(s.pending_buf + s.pending,
              //    s.gzhead.extra + s.gzindex, copy);
              s.pending_buf.set(s.gzhead.extra.subarray(s.gzindex, s.gzindex + copy), s.pending);
              s.pending = s.pending_buf_size;
              //--- HCRC_UPDATE(beg) ---//
              if (s.gzhead.hcrc && s.pending > beg) {
                strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
              }
              //---//
              s.gzindex += copy;
              flush_pending(strm);
              if (s.pending !== 0) {
                s.last_flush = -1;
                return Z_OK$3;
              }
              beg = 0;
              left -= copy;
            }
            // JS specific: s.gzhead.extra may be TypedArray or Array for backward compatibility
            //              TypedArray.slice and TypedArray.from don't exist in IE10-IE11
            let gzhead_extra = new Uint8Array(s.gzhead.extra);
            // zmemcpy(s->pending_buf + s->pending,
            //     s->gzhead->extra + s->gzindex, left);
            s.pending_buf.set(gzhead_extra.subarray(s.gzindex, s.gzindex + left), s.pending);
            s.pending += left;
            //--- HCRC_UPDATE(beg) ---//
            if (s.gzhead.hcrc && s.pending > beg) {
              strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
            }
            //---//
            s.gzindex = 0;
          }
          s.status = NAME_STATE;
        }
        if (s.status === NAME_STATE) {
          if (s.gzhead.name/* != Z_NULL*/) {
            let beg = s.pending;   /* start of bytes to update crc */
            let val;
            do {
              if (s.pending === s.pending_buf_size) {
                //--- HCRC_UPDATE(beg) ---//
                if (s.gzhead.hcrc && s.pending > beg) {
                  strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
                }
                //---//
                flush_pending(strm);
                if (s.pending !== 0) {
                  s.last_flush = -1;
                  return Z_OK$3;
                }
                beg = 0;
              }
              // JS specific: little magic to add zero terminator to end of string
              if (s.gzindex < s.gzhead.name.length) {
                val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
              } else {
                val = 0;
              }
              put_byte(s, val);
            } while (val !== 0);
            //--- HCRC_UPDATE(beg) ---//
            if (s.gzhead.hcrc && s.pending > beg) {
              strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
            }
            //---//
            s.gzindex = 0;
          }
          s.status = COMMENT_STATE;
        }
        if (s.status === COMMENT_STATE) {
          if (s.gzhead.comment/* != Z_NULL*/) {
            let beg = s.pending;   /* start of bytes to update crc */
            let val;
            do {
              if (s.pending === s.pending_buf_size) {
                //--- HCRC_UPDATE(beg) ---//
                if (s.gzhead.hcrc && s.pending > beg) {
                  strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
                }
                //---//
                flush_pending(strm);
                if (s.pending !== 0) {
                  s.last_flush = -1;
                  return Z_OK$3;
                }
                beg = 0;
              }
              // JS specific: little magic to add zero terminator to end of string
              if (s.gzindex < s.gzhead.comment.length) {
                val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
              } else {
                val = 0;
              }
              put_byte(s, val);
            } while (val !== 0);
            //--- HCRC_UPDATE(beg) ---//
            if (s.gzhead.hcrc && s.pending > beg) {
              strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
            }
            //---//
          }
          s.status = HCRC_STATE;
        }
        if (s.status === HCRC_STATE) {
          if (s.gzhead.hcrc) {
            if (s.pending + 2 > s.pending_buf_size) {
              flush_pending(strm);
              if (s.pending !== 0) {
                s.last_flush = -1;
                return Z_OK$3;
              }
            }
            put_byte(s, strm.adler & 0xff);
            put_byte(s, (strm.adler >> 8) & 0xff);
            strm.adler = 0; //crc32(0L, Z_NULL, 0);
          }
          s.status = BUSY_STATE;
    
          /* Compression must start with an empty pending buffer */
          flush_pending(strm);
          if (s.pending !== 0) {
            s.last_flush = -1;
            return Z_OK$3;
          }
        }
      //#endif
    
        /* Start a new block or continue the current one.
         */
        if (strm.avail_in !== 0 || s.lookahead !== 0 ||
          (flush !== Z_NO_FLUSH$2 && s.status !== FINISH_STATE)) {
          let bstate = s.level === 0 ? deflate_stored(s, flush) :
                       s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
                       s.strategy === Z_RLE ? deflate_rle(s, flush) :
                       configuration_table[s.level].func(s, flush);
    
          if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
            s.status = FINISH_STATE;
          }
          if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
            if (strm.avail_out === 0) {
              s.last_flush = -1;
              /* avoid BUF_ERROR next call, see above */
            }
            return Z_OK$3;
            /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
             * of deflate should use the same flush parameter to make sure
             * that the flush is complete. So we don't have to output an
             * empty block here, this will be done at next call. This also
             * ensures that for a very small output buffer, we emit at most
             * one empty block.
             */
          }
          if (bstate === BS_BLOCK_DONE) {
            if (flush === Z_PARTIAL_FLUSH) {
              _tr_align(s);
            }
            else if (flush !== Z_BLOCK$1) { /* FULL_FLUSH or SYNC_FLUSH */
    
              _tr_stored_block(s, 0, 0, false);
              /* For a full flush, this empty block will be recognized
               * as a special marker by inflate_sync().
               */
              if (flush === Z_FULL_FLUSH$1) {
                /*** CLEAR_HASH(s); ***/             /* forget history */
                zero(s.head); // Fill with NIL (= 0);
    
                if (s.lookahead === 0) {
                  s.strstart = 0;
                  s.block_start = 0;
                  s.insert = 0;
                }
              }
            }
            flush_pending(strm);
            if (strm.avail_out === 0) {
              s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
              return Z_OK$3;
            }
          }
        }
    
        if (flush !== Z_FINISH$3) { return Z_OK$3; }
        if (s.wrap <= 0) { return Z_STREAM_END$3; }
    
        /* Write the trailer */
        if (s.wrap === 2) {
          put_byte(s, strm.adler & 0xff);
          put_byte(s, (strm.adler >> 8) & 0xff);
          put_byte(s, (strm.adler >> 16) & 0xff);
          put_byte(s, (strm.adler >> 24) & 0xff);
          put_byte(s, strm.total_in & 0xff);
          put_byte(s, (strm.total_in >> 8) & 0xff);
          put_byte(s, (strm.total_in >> 16) & 0xff);
          put_byte(s, (strm.total_in >> 24) & 0xff);
        }
        else
        {
          putShortMSB(s, strm.adler >>> 16);
          putShortMSB(s, strm.adler & 0xffff);
        }
    
        flush_pending(strm);
        /* If avail_out is zero, the application will call deflate again
         * to flush the rest.
         */
        if (s.wrap > 0) { s.wrap = -s.wrap; }
        /* write the trailer only once! */
        return s.pending !== 0 ? Z_OK$3 : Z_STREAM_END$3;
      };
    
    
      const deflateEnd = (strm) => {
    
        if (deflateStateCheck(strm)) {
          return Z_STREAM_ERROR$2;
        }
    
        const status = strm.state.status;
    
        strm.state = null;
    
        return status === BUSY_STATE ? err(strm, Z_DATA_ERROR$2) : Z_OK$3;
      };
    
    
      /* =========================================================================
       * Initializes the compression dictionary from the given byte
       * sequence without producing any compressed output.
       */
      const deflateSetDictionary = (strm, dictionary) => {
    
        let dictLength = dictionary.length;
    
        if (deflateStateCheck(strm)) {
          return Z_STREAM_ERROR$2;
        }
    
        const s = strm.state;
        const wrap = s.wrap;
    
        if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
          return Z_STREAM_ERROR$2;
        }
    
        /* when using zlib wrappers, compute Adler-32 for provided dictionary */
        if (wrap === 1) {
          /* adler32(strm->adler, dictionary, dictLength); */
          strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0);
        }
    
        s.wrap = 0;   /* avoid computing Adler-32 in read_buf */
    
        /* if dictionary would fill window, just replace the history */
        if (dictLength >= s.w_size) {
          if (wrap === 0) {            /* already empty otherwise */
            /*** CLEAR_HASH(s); ***/
            zero(s.head); // Fill with NIL (= 0);
            s.strstart = 0;
            s.block_start = 0;
            s.insert = 0;
          }
          /* use the tail */
          // dictionary = dictionary.slice(dictLength - s.w_size);
          let tmpDict = new Uint8Array(s.w_size);
          tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);
          dictionary = tmpDict;
          dictLength = s.w_size;
        }
        /* insert dictionary into window and hash */
        const avail = strm.avail_in;
        const next = strm.next_in;
        const input = strm.input;
        strm.avail_in = dictLength;
        strm.next_in = 0;
        strm.input = dictionary;
        fill_window(s);
        while (s.lookahead >= MIN_MATCH) {
          let str = s.strstart;
          let n = s.lookahead - (MIN_MATCH - 1);
          do {
            /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
            s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);
    
            s.prev[str & s.w_mask] = s.head[s.ins_h];
    
            s.head[s.ins_h] = str;
            str++;
          } while (--n);
          s.strstart = str;
          s.lookahead = MIN_MATCH - 1;
          fill_window(s);
        }
        s.strstart += s.lookahead;
        s.block_start = s.strstart;
        s.insert = s.lookahead;
        s.lookahead = 0;
        s.match_length = s.prev_length = MIN_MATCH - 1;
        s.match_available = 0;
        strm.next_in = next;
        strm.input = input;
        strm.avail_in = avail;
        s.wrap = wrap;
        return Z_OK$3;
      };
    
    
      var deflateInit_1 = deflateInit;
      var deflateInit2_1 = deflateInit2;
      var deflateReset_1 = deflateReset;
      var deflateResetKeep_1 = deflateResetKeep;
      var deflateSetHeader_1 = deflateSetHeader;
      var deflate_2$1 = deflate$2;
      var deflateEnd_1 = deflateEnd;
      var deflateSetDictionary_1 = deflateSetDictionary;
      var deflateInfo = 'pako deflate (from Nodeca project)';
    
      /* Not implemented
      module.exports.deflateBound = deflateBound;
      module.exports.deflateCopy = deflateCopy;
      module.exports.deflateGetDictionary = deflateGetDictionary;
      module.exports.deflateParams = deflateParams;
      module.exports.deflatePending = deflatePending;
      module.exports.deflatePrime = deflatePrime;
      module.exports.deflateTune = deflateTune;
      */
    
      var deflate_1$2 = {
          deflateInit: deflateInit_1,
          deflateInit2: deflateInit2_1,
          deflateReset: deflateReset_1,
          deflateResetKeep: deflateResetKeep_1,
          deflateSetHeader: deflateSetHeader_1,
          deflate: deflate_2$1,
          deflateEnd: deflateEnd_1,
          deflateSetDictionary: deflateSetDictionary_1,
          deflateInfo: deflateInfo
      };
    
      const _has = (obj, key) => {
        return Object.prototype.hasOwnProperty.call(obj, key);
      };
    
      var assign = function (obj /*from1, from2, from3, ...*/) {
        const sources = Array.prototype.slice.call(arguments, 1);
        while (sources.length) {
          const source = sources.shift();
          if (!source) { continue; }
    
          if (typeof source !== 'object') {
            throw new TypeError(source + 'must be non-object');
          }
    
          for (const p in source) {
            if (_has(source, p)) {
              obj[p] = source[p];
            }
          }
        }
    
        return obj;
      };
    
    
      // Join array of chunks to single array.
      var flattenChunks = (chunks) => {
        // calculate data length
        let len = 0;
    
        for (let i = 0, l = chunks.length; i < l; i++) {
          len += chunks[i].length;
        }
    
        // join chunks
        const result = new Uint8Array(len);
    
        for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {
          let chunk = chunks[i];
          result.set(chunk, pos);
          pos += chunk.length;
        }
    
        return result;
      };
    
      var common = {
          assign: assign,
          flattenChunks: flattenChunks
      };
    
      // String encode/decode helpers
    
    
      // Quick check if we can use fast array to bin string conversion
      //
      // - apply(Array) can fail on Android 2.2
      // - apply(Uint8Array) can fail on iOS 5.1 Safari
      //
      let STR_APPLY_UIA_OK = true;
    
      try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
    
    
      // Table with utf8 lengths (calculated by first byte of sequence)
      // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
      // because max possible codepoint is 0x10ffff
      const _utf8len = new Uint8Array(256);
      for (let q = 0; q < 256; q++) {
        _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
      }
      _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
    
    
      // convert string to array (typed, when possible)
      var string2buf = (str) => {
        if (typeof TextEncoder === 'function' && TextEncoder.prototype.encode) {
          return new TextEncoder().encode(str);
        }
    
        let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
    
        // count binary size
        for (m_pos = 0; m_pos < str_len; m_pos++) {
          c = str.charCodeAt(m_pos);
          if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
            c2 = str.charCodeAt(m_pos + 1);
            if ((c2 & 0xfc00) === 0xdc00) {
              c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
              m_pos++;
            }
          }
          buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
        }
    
        // allocate buffer
        buf = new Uint8Array(buf_len);
    
        // convert
        for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
          c = str.charCodeAt(m_pos);
          if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
            c2 = str.charCodeAt(m_pos + 1);
            if ((c2 & 0xfc00) === 0xdc00) {
              c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
              m_pos++;
            }
          }
          if (c < 0x80) {
            /* one byte */
            buf[i++] = c;
          } else if (c < 0x800) {
            /* two bytes */
            buf[i++] = 0xC0 | (c >>> 6);
            buf[i++] = 0x80 | (c & 0x3f);
          } else if (c < 0x10000) {
            /* three bytes */
            buf[i++] = 0xE0 | (c >>> 12);
            buf[i++] = 0x80 | (c >>> 6 & 0x3f);
            buf[i++] = 0x80 | (c & 0x3f);
          } else {
            /* four bytes */
            buf[i++] = 0xf0 | (c >>> 18);
            buf[i++] = 0x80 | (c >>> 12 & 0x3f);
            buf[i++] = 0x80 | (c >>> 6 & 0x3f);
            buf[i++] = 0x80 | (c & 0x3f);
          }
        }
    
        return buf;
      };
    
      // Helper
      const buf2binstring = (buf, len) => {
        // On Chrome, the arguments in a function call that are allowed is `65534`.
        // If the length of the buffer is smaller than that, we can use this optimization,
        // otherwise we will take a slower path.
        if (len < 65534) {
          if (buf.subarray && STR_APPLY_UIA_OK) {
            return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));
          }
        }
    
        let result = '';
        for (let i = 0; i < len; i++) {
          result += String.fromCharCode(buf[i]);
        }
        return result;
      };
    
    
      // convert array to string
      var buf2string = (buf, max) => {
        const len = max || buf.length;
    
        if (typeof TextDecoder === 'function' && TextDecoder.prototype.decode) {
          return new TextDecoder().decode(buf.subarray(0, max));
        }
    
        let i, out;
    
        // Reserve max possible length (2 words per char)
        // NB: by unknown reasons, Array is significantly faster for
        //     String.fromCharCode.apply than Uint16Array.
        const utf16buf = new Array(len * 2);
    
        for (out = 0, i = 0; i < len;) {
          let c = buf[i++];
          // quick process ascii
          if (c < 0x80) { utf16buf[out++] = c; continue; }
    
          let c_len = _utf8len[c];
          // skip 5 & 6 byte codes
          if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
    
          // apply mask on first byte
          c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
          // join the rest
          while (c_len > 1 && i < len) {
            c = (c << 6) | (buf[i++] & 0x3f);
            c_len--;
          }
    
          // terminated by end of string?
          if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
    
          if (c < 0x10000) {
            utf16buf[out++] = c;
          } else {
            c -= 0x10000;
            utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
            utf16buf[out++] = 0xdc00 | (c & 0x3ff);
          }
        }
    
        return buf2binstring(utf16buf, out);
      };
    
    
      // Calculate max possible position in utf8 buffer,
      // that will not break sequence. If that's not possible
      // - (very small limits) return max size as is.
      //
      // buf[] - utf8 bytes array
      // max   - length limit (mandatory);
      var utf8border = (buf, max) => {
    
        max = max || buf.length;
        if (max > buf.length) { max = buf.length; }
    
        // go back from last position, until start of sequence found
        let pos = max - 1;
        while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
    
        // Very small and broken sequence,
        // return max, because we should return something anyway.
        if (pos < 0) { return max; }
    
        // If we came to start of buffer - that means buffer is too small,
        // return max too.
        if (pos === 0) { return max; }
    
        return (pos + _utf8len[buf[pos]] > max) ? pos : max;
      };
    
      var strings = {
          string2buf: string2buf,
          buf2string: buf2string,
          utf8border: utf8border
      };
    
      // (C) 1995-2013 Jean-loup Gailly and Mark Adler
      // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
      //
      // This software is provided 'as-is', without any express or implied
      // warranty. In no event will the authors be held liable for any damages
      // arising from the use of this software.
      //
      // Permission is granted to anyone to use this software for any purpose,
      // including commercial applications, and to alter it and redistribute it
      // freely, subject to the following restrictions:
      //
      // 1. The origin of this software must not be misrepresented; you must not
      //   claim that you wrote the original software. If you use this software
      //   in a product, an acknowledgment in the product documentation would be
      //   appreciated but is not required.
      // 2. Altered source versions must be plainly marked as such, and must not be
      //   misrepresented as being the original software.
      // 3. This notice may not be removed or altered from any source distribution.
    
      function ZStream() {
        /* next input byte */
        this.input = null; // JS specific, because we have no pointers
        this.next_in = 0;
        /* number of bytes available at input */
        this.avail_in = 0;
        /* total number of input bytes read so far */
        this.total_in = 0;
        /* next output byte should be put there */
        this.output = null; // JS specific, because we have no pointers
        this.next_out = 0;
        /* remaining free space at output */
        this.avail_out = 0;
        /* total number of bytes output so far */
        this.total_out = 0;
        /* last error message, NULL if no error */
        this.msg = ''/*Z_NULL*/;
        /* not visible by applications */
        this.state = null;
        /* best guess about the data type: binary or text */
        this.data_type = 2/*Z_UNKNOWN*/;
        /* adler32 value of the uncompressed data */
        this.adler = 0;
      }
    
      var zstream = ZStream;
    
      const toString$1 = Object.prototype.toString;
    
      /* Public constants ==========================================================*/
      /* ===========================================================================*/
    
      const {
        Z_NO_FLUSH: Z_NO_FLUSH$1, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH: Z_FINISH$2,
        Z_OK: Z_OK$2, Z_STREAM_END: Z_STREAM_END$2,
        Z_DEFAULT_COMPRESSION,
        Z_DEFAULT_STRATEGY,
        Z_DEFLATED: Z_DEFLATED$1
      } = constants$2;
    
      /* ===========================================================================*/
    
    
      /**
       * class Deflate
       *
       * Generic JS-style wrapper for zlib calls. If you don't need
       * streaming behaviour - use more simple functions: [[deflate]],
       * [[deflateRaw]] and [[gzip]].
       **/
    
      /* internal
       * Deflate.chunks -> Array
       *
       * Chunks of output data, if [[Deflate#onData]] not overridden.
       **/
    
      /**
       * Deflate.result -> Uint8Array
       *
       * Compressed result, generated by default [[Deflate#onData]]
       * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
       * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
       **/
    
      /**
       * Deflate.err -> Number
       *
       * Error code after deflate finished. 0 (Z_OK) on success.
       * You will not need it in real life, because deflate errors
       * are possible only on wrong options or bad `onData` / `onEnd`
       * custom handlers.
       **/
    
      /**
       * Deflate.msg -> String
       *
       * Error message, if [[Deflate.err]] != 0
       **/
    
    
      /**
       * new Deflate(options)
       * - options (Object): zlib deflate options.
       *
       * Creates new deflator instance with specified params. Throws exception
       * on bad params. Supported options:
       *
       * - `level`
       * - `windowBits`
       * - `memLevel`
       * - `strategy`
       * - `dictionary`
       *
       * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
       * for more information on these.
       *
       * Additional options, for internal needs:
       *
       * - `chunkSize` - size of generated data chunks (16K by default)
       * - `raw` (Boolean) - do raw deflate
       * - `gzip` (Boolean) - create gzip wrapper
       * - `header` (Object) - custom header for gzip
       *   - `text` (Boolean) - true if compressed data believed to be text
       *   - `time` (Number) - modification time, unix timestamp
       *   - `os` (Number) - operation system code
       *   - `extra` (Array) - array of bytes with extra data (max 65536)
       *   - `name` (String) - file name (binary string)
       *   - `comment` (String) - comment (binary string)
       *   - `hcrc` (Boolean) - true if header crc should be added
       *
       * ##### Example:
       *
       * ```javascript
       * const pako = require('pako')
       *   , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])
       *   , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);
       *
       * const deflate = new pako.Deflate({ level: 3});
       *
       * deflate.push(chunk1, false);
       * deflate.push(chunk2, true);  // true -> last chunk
       *
       * if (deflate.err) { throw new Error(deflate.err); }
       *
       * console.log(deflate.result);
       * ```
       **/
      function Deflate$1(options) {
        this.options = common.assign({
          level: Z_DEFAULT_COMPRESSION,
          method: Z_DEFLATED$1,
          chunkSize: 16384,
          windowBits: 15,
          memLevel: 8,
          strategy: Z_DEFAULT_STRATEGY
        }, options || {});
    
        let opt = this.options;
    
        if (opt.raw && (opt.windowBits > 0)) {
          opt.windowBits = -opt.windowBits;
        }
    
        else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
          opt.windowBits += 16;
        }
    
        this.err    = 0;      // error code, if happens (0 = Z_OK)
        this.msg    = '';     // error message
        this.ended  = false;  // used to avoid multiple onEnd() calls
        this.chunks = [];     // chunks of compressed data
    
        this.strm = new zstream();
        this.strm.avail_out = 0;
    
        let status = deflate_1$2.deflateInit2(
          this.strm,
          opt.level,
          opt.method,
          opt.windowBits,
          opt.memLevel,
          opt.strategy
        );
    
        if (status !== Z_OK$2) {
          throw new Error(messages[status]);
        }
    
        if (opt.header) {
          deflate_1$2.deflateSetHeader(this.strm, opt.header);
        }
    
        if (opt.dictionary) {
          let dict;
          // Convert data if needed
          if (typeof opt.dictionary === 'string') {
            // If we need to compress text, change encoding to utf8.
            dict = strings.string2buf(opt.dictionary);
          } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') {
            dict = new Uint8Array(opt.dictionary);
          } else {
            dict = opt.dictionary;
          }
    
          status = deflate_1$2.deflateSetDictionary(this.strm, dict);
    
          if (status !== Z_OK$2) {
            throw new Error(messages[status]);
          }
    
          this._dict_set = true;
        }
      }
    
      /**
       * Deflate#push(data[, flush_mode]) -> Boolean
       * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be
       *   converted to utf8 byte sequence.
       * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
       *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
       *
       * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
       * new compressed chunks. Returns `true` on success. The last data block must
       * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending
       * buffers and call [[Deflate#onEnd]].
       *
       * On fail call [[Deflate#onEnd]] with error code and return false.
       *
       * ##### Example
       *
       * ```javascript
       * push(chunk, false); // push one of data chunks
       * ...
       * push(chunk, true);  // push last chunk
       * ```
       **/
      Deflate$1.prototype.push = function (data, flush_mode) {
        const strm = this.strm;
        const chunkSize = this.options.chunkSize;
        let status, _flush_mode;
    
        if (this.ended) { return false; }
    
        if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;
        else _flush_mode = flush_mode === true ? Z_FINISH$2 : Z_NO_FLUSH$1;
    
        // Convert data if needed
        if (typeof data === 'string') {
          // If we need to compress text, change encoding to utf8.
          strm.input = strings.string2buf(data);
        } else if (toString$1.call(data) === '[object ArrayBuffer]') {
          strm.input = new Uint8Array(data);
        } else {
          strm.input = data;
        }
    
        strm.next_in = 0;
        strm.avail_in = strm.input.length;
    
        for (;;) {
          if (strm.avail_out === 0) {
            strm.output = new Uint8Array(chunkSize);
            strm.next_out = 0;
            strm.avail_out = chunkSize;
          }
    
          // Make sure avail_out > 6 to avoid repeating markers
          if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH) && strm.avail_out <= 6) {
            this.onData(strm.output.subarray(0, strm.next_out));
            strm.avail_out = 0;
            continue;
          }
    
          status = deflate_1$2.deflate(strm, _flush_mode);
    
          // Ended => flush and finish
          if (status === Z_STREAM_END$2) {
            if (strm.next_out > 0) {
              this.onData(strm.output.subarray(0, strm.next_out));
            }
            status = deflate_1$2.deflateEnd(this.strm);
            this.onEnd(status);
            this.ended = true;
            return status === Z_OK$2;
          }
    
          // Flush if out buffer full
          if (strm.avail_out === 0) {
            this.onData(strm.output);
            continue;
          }
    
          // Flush if requested and has data
          if (_flush_mode > 0 && strm.next_out > 0) {
            this.onData(strm.output.subarray(0, strm.next_out));
            strm.avail_out = 0;
            continue;
          }
    
          if (strm.avail_in === 0) break;
        }
    
        return true;
      };
    
    
      /**
       * Deflate#onData(chunk) -> Void
       * - chunk (Uint8Array): output data.
       *
       * By default, stores data blocks in `chunks[]` property and glue
       * those in `onEnd`. Override this handler, if you need another behaviour.
       **/
      Deflate$1.prototype.onData = function (chunk) {
        this.chunks.push(chunk);
      };
    
    
      /**
       * Deflate#onEnd(status) -> Void
       * - status (Number): deflate status. 0 (Z_OK) on success,
       *   other if not.
       *
       * Called once after you tell deflate that the input stream is
       * complete (Z_FINISH). By default - join collected chunks,
       * free memory and fill `results` / `err` properties.
       **/
      Deflate$1.prototype.onEnd = function (status) {
        // On success - join
        if (status === Z_OK$2) {
          this.result = common.flattenChunks(this.chunks);
        }
        this.chunks = [];
        this.err = status;
        this.msg = this.strm.msg;
      };
    
    
      /**
       * deflate(data[, options]) -> Uint8Array
       * - data (Uint8Array|ArrayBuffer|String): input data to compress.
       * - options (Object): zlib deflate options.
       *
       * Compress `data` with deflate algorithm and `options`.
       *
       * Supported options are:
       *
       * - level
       * - windowBits
       * - memLevel
       * - strategy
       * - dictionary
       *
       * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
       * for more information on these.
       *
       * Sugar (options):
       *
       * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
       *   negative windowBits implicitly.
       *
       * ##### Example:
       *
       * ```javascript
       * const pako = require('pako')
       * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);
       *
       * console.log(pako.deflate(data));
       * ```
       **/
      function deflate$1(input, options) {
        const deflator = new Deflate$1(options);
    
        deflator.push(input, true);
    
        // That will never happens, if you don't cheat with options :)
        if (deflator.err) { throw deflator.msg || messages[deflator.err]; }
    
        return deflator.result;
      }
    
    
      /**
       * deflateRaw(data[, options]) -> Uint8Array
       * - data (Uint8Array|ArrayBuffer|String): input data to compress.
       * - options (Object): zlib deflate options.
       *
       * The same as [[deflate]], but creates raw data, without wrapper
       * (header and adler32 crc).
       **/
      function deflateRaw$1(input, options) {
        options = options || {};
        options.raw = true;
        return deflate$1(input, options);
      }
    
    
      /**
       * gzip(data[, options]) -> Uint8Array
       * - data (Uint8Array|ArrayBuffer|String): input data to compress.
       * - options (Object): zlib deflate options.
       *
       * The same as [[deflate]], but create gzip wrapper instead of
       * deflate one.
       **/
      function gzip$1(input, options) {
        options = options || {};
        options.gzip = true;
        return deflate$1(input, options);
      }
    
    
      var Deflate_1$1 = Deflate$1;
      var deflate_2 = deflate$1;
      var deflateRaw_1$1 = deflateRaw$1;
      var gzip_1$1 = gzip$1;
      var constants$1 = constants$2;
    
      var deflate_1$1 = {
          Deflate: Deflate_1$1,
          deflate: deflate_2,
          deflateRaw: deflateRaw_1$1,
          gzip: gzip_1$1,
          constants: constants$1
      };
    
      // (C) 1995-2013 Jean-loup Gailly and Mark Adler
      // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
      //
      // This software is provided 'as-is', without any express or implied
      // warranty. In no event will the authors be held liable for any damages
      // arising from the use of this software.
      //
      // Permission is granted to anyone to use this software for any purpose,
      // including commercial applications, and to alter it and redistribute it
      // freely, subject to the following restrictions:
      //
      // 1. The origin of this software must not be misrepresented; you must not
      //   claim that you wrote the original software. If you use this software
      //   in a product, an acknowledgment in the product documentation would be
      //   appreciated but is not required.
      // 2. Altered source versions must be plainly marked as such, and must not be
      //   misrepresented as being the original software.
      // 3. This notice may not be removed or altered from any source distribution.
    
      // See state defs from inflate.js
      const BAD$1 = 16209;       /* got a data error -- remain here until reset */
      const TYPE$1 = 16191;      /* i: waiting for type bits, including last-flag bit */
    
      /*
         Decode literal, length, and distance codes and write out the resulting
         literal and match bytes until either not enough input or output is
         available, an end-of-block is encountered, or a data error is encountered.
         When large enough input and output buffers are supplied to inflate(), for
         example, a 16K input buffer and a 64K output buffer, more than 95% of the
         inflate execution time is spent in this routine.
    
         Entry assumptions:
    
              state.mode === LEN
              strm.avail_in >= 6
              strm.avail_out >= 258
              start >= strm.avail_out
              state.bits < 8
    
         On return, state.mode is one of:
    
              LEN -- ran out of enough output space or enough available input
              TYPE -- reached end of block code, inflate() to interpret next block
              BAD -- error in block data
    
         Notes:
    
          - The maximum input bits used by a length/distance pair is 15 bits for the
            length code, 5 bits for the length extra, 15 bits for the distance code,
            and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
            Therefore if strm.avail_in >= 6, then there is enough input to avoid
            checking for available input while decoding.
    
          - The maximum bytes that a single length/distance pair can output is 258
            bytes, which is the maximum length that can be coded.  inflate_fast()
            requires strm.avail_out >= 258 for each loop to avoid checking for
            output space.
       */
      var inffast = function inflate_fast(strm, start) {
        let _in;                    /* local strm.input */
        let last;                   /* have enough input while in < last */
        let _out;                   /* local strm.output */
        let beg;                    /* inflate()'s initial strm.output */
        let end;                    /* while out < end, enough space available */
      //#ifdef INFLATE_STRICT
        let dmax;                   /* maximum distance from zlib header */
      //#endif
        let wsize;                  /* window size or zero if not using window */
        let whave;                  /* valid bytes in the window */
        let wnext;                  /* window write index */
        // Use `s_window` instead `window`, avoid conflict with instrumentation tools
        let s_window;               /* allocated sliding window, if wsize != 0 */
        let hold;                   /* local strm.hold */
        let bits;                   /* local strm.bits */
        let lcode;                  /* local strm.lencode */
        let dcode;                  /* local strm.distcode */
        let lmask;                  /* mask for first level of length codes */
        let dmask;                  /* mask for first level of distance codes */
        let here;                   /* retrieved table entry */
        let op;                     /* code bits, operation, extra bits, or */
                                    /*  window position, window bytes to copy */
        let len;                    /* match length, unused bytes */
        let dist;                   /* match distance */
        let from;                   /* where to copy match from */
        let from_source;
    
    
        let input, output; // JS specific, because we have no pointers
    
        /* copy state to local variables */
        const state = strm.state;
        //here = state.here;
        _in = strm.next_in;
        input = strm.input;
        last = _in + (strm.avail_in - 5);
        _out = strm.next_out;
        output = strm.output;
        beg = _out - (start - strm.avail_out);
        end = _out + (strm.avail_out - 257);
      //#ifdef INFLATE_STRICT
        dmax = state.dmax;
      //#endif
        wsize = state.wsize;
        whave = state.whave;
        wnext = state.wnext;
        s_window = state.window;
        hold = state.hold;
        bits = state.bits;
        lcode = state.lencode;
        dcode = state.distcode;
        lmask = (1 << state.lenbits) - 1;
        dmask = (1 << state.distbits) - 1;
    
    
        /* decode literals and length/distances until end-of-block or not enough
           input data or output space */
    
        top:
        do {
          if (bits < 15) {
            hold += input[_in++] << bits;
            bits += 8;
            hold += input[_in++] << bits;
            bits += 8;
          }
    
          here = lcode[hold & lmask];
    
          dolen:
          for (;;) { // Goto emulation
            op = here >>> 24/*here.bits*/;
            hold >>>= op;
            bits -= op;
            op = (here >>> 16) & 0xff/*here.op*/;
            if (op === 0) {                          /* literal */
              //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
              //        "inflate:         literal '%c'\n" :
              //        "inflate:         literal 0x%02x\n", here.val));
              output[_out++] = here & 0xffff/*here.val*/;
            }
            else if (op & 16) {                     /* length base */
              len = here & 0xffff/*here.val*/;
              op &= 15;                           /* number of extra bits */
              if (op) {
                if (bits < op) {
                  hold += input[_in++] << bits;
                  bits += 8;
                }
                len += hold & ((1 << op) - 1);
                hold >>>= op;
                bits -= op;
              }
              //Tracevv((stderr, "inflate:         length %u\n", len));
              if (bits < 15) {
                hold += input[_in++] << bits;
                bits += 8;
                hold += input[_in++] << bits;
                bits += 8;
              }
              here = dcode[hold & dmask];
    
              dodist:
              for (;;) { // goto emulation
                op = here >>> 24/*here.bits*/;
                hold >>>= op;
                bits -= op;
                op = (here >>> 16) & 0xff/*here.op*/;
    
                if (op & 16) {                      /* distance base */
                  dist = here & 0xffff/*here.val*/;
                  op &= 15;                       /* number of extra bits */
                  if (bits < op) {
                    hold += input[_in++] << bits;
                    bits += 8;
                    if (bits < op) {
                      hold += input[_in++] << bits;
                      bits += 8;
                    }
                  }
                  dist += hold & ((1 << op) - 1);
      //#ifdef INFLATE_STRICT
                  if (dist > dmax) {
                    strm.msg = 'invalid distance too far back';
                    state.mode = BAD$1;
                    break top;
                  }
      //#endif
                  hold >>>= op;
                  bits -= op;
                  //Tracevv((stderr, "inflate:         distance %u\n", dist));
                  op = _out - beg;                /* max distance in output */
                  if (dist > op) {                /* see if copy from window */
                    op = dist - op;               /* distance back in window */
                    if (op > whave) {
                      if (state.sane) {
                        strm.msg = 'invalid distance too far back';
                        state.mode = BAD$1;
                        break top;
                      }
    
      // (!) This block is disabled in zlib defaults,
      // don't enable it for binary compatibility
      //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
      //                if (len <= op - whave) {
      //                  do {
      //                    output[_out++] = 0;
      //                  } while (--len);
      //                  continue top;
      //                }
      //                len -= op - whave;
      //                do {
      //                  output[_out++] = 0;
      //                } while (--op > whave);
      //                if (op === 0) {
      //                  from = _out - dist;
      //                  do {
      //                    output[_out++] = output[from++];
      //                  } while (--len);
      //                  continue top;
      //                }
      //#endif
                    }
                    from = 0; // window index
                    from_source = s_window;
                    if (wnext === 0) {           /* very common case */
                      from += wsize - op;
                      if (op < len) {         /* some from window */
                        len -= op;
                        do {
                          output[_out++] = s_window[from++];
                        } while (--op);
                        from = _out - dist;  /* rest from output */
                        from_source = output;
                      }
                    }
                    else if (wnext < op) {      /* wrap around window */
                      from += wsize + wnext - op;
                      op -= wnext;
                      if (op < len) {         /* some from end of window */
                        len -= op;
                        do {
                          output[_out++] = s_window[from++];
                        } while (--op);
                        from = 0;
                        if (wnext < len) {  /* some from start of window */
                          op = wnext;
                          len -= op;
                          do {
                            output[_out++] = s_window[from++];
                          } while (--op);
                          from = _out - dist;      /* rest from output */
                          from_source = output;
                        }
                      }
                    }
                    else {                      /* contiguous in window */
                      from += wnext - op;
                      if (op < len) {         /* some from window */
                        len -= op;
                        do {
                          output[_out++] = s_window[from++];
                        } while (--op);
                        from = _out - dist;  /* rest from output */
                        from_source = output;
                      }
                    }
                    while (len > 2) {
                      output[_out++] = from_source[from++];
                      output[_out++] = from_source[from++];
                      output[_out++] = from_source[from++];
                      len -= 3;
                    }
                    if (len) {
                      output[_out++] = from_source[from++];
                      if (len > 1) {
                        output[_out++] = from_source[from++];
                      }
                    }
                  }
                  else {
                    from = _out - dist;          /* copy direct from output */
                    do {                        /* minimum length is three */
                      output[_out++] = output[from++];
                      output[_out++] = output[from++];
                      output[_out++] = output[from++];
                      len -= 3;
                    } while (len > 2);
                    if (len) {
                      output[_out++] = output[from++];
                      if (len > 1) {
                        output[_out++] = output[from++];
                      }
                    }
                  }
                }
                else if ((op & 64) === 0) {          /* 2nd level distance code */
                  here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
                  continue dodist;
                }
                else {
                  strm.msg = 'invalid distance code';
                  state.mode = BAD$1;
                  break top;
                }
    
                break; // need to emulate goto via "continue"
              }
            }
            else if ((op & 64) === 0) {              /* 2nd level length code */
              here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
              continue dolen;
            }
            else if (op & 32) {                     /* end-of-block */
              //Tracevv((stderr, "inflate:         end of block\n"));
              state.mode = TYPE$1;
              break top;
            }
            else {
              strm.msg = 'invalid literal/length code';
              state.mode = BAD$1;
              break top;
            }
    
            break; // need to emulate goto via "continue"
          }
        } while (_in < last && _out < end);
    
        /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
        len = bits >> 3;
        _in -= len;
        bits -= len << 3;
        hold &= (1 << bits) - 1;
    
        /* update state and return */
        strm.next_in = _in;
        strm.next_out = _out;
        strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
        strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
        state.hold = hold;
        state.bits = bits;
        return;
      };
    
      // (C) 1995-2013 Jean-loup Gailly and Mark Adler
      // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
      //
      // This software is provided 'as-is', without any express or implied
      // warranty. In no event will the authors be held liable for any damages
      // arising from the use of this software.
      //
      // Permission is granted to anyone to use this software for any purpose,
      // including commercial applications, and to alter it and redistribute it
      // freely, subject to the following restrictions:
      //
      // 1. The origin of this software must not be misrepresented; you must not
      //   claim that you wrote the original software. If you use this software
      //   in a product, an acknowledgment in the product documentation would be
      //   appreciated but is not required.
      // 2. Altered source versions must be plainly marked as such, and must not be
      //   misrepresented as being the original software.
      // 3. This notice may not be removed or altered from any source distribution.
    
      const MAXBITS = 15;
      const ENOUGH_LENS$1 = 852;
      const ENOUGH_DISTS$1 = 592;
      //const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
    
      const CODES$1 = 0;
      const LENS$1 = 1;
      const DISTS$1 = 2;
    
      const lbase = new Uint16Array([ /* Length codes 257..285 base */
        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
      ]);
    
      const lext = new Uint8Array([ /* Length codes 257..285 extra */
        16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
      ]);
    
      const dbase = new Uint16Array([ /* Distance codes 0..29 base */
        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
        8193, 12289, 16385, 24577, 0, 0
      ]);
    
      const dext = new Uint8Array([ /* Distance codes 0..29 extra */
        16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
        23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
        28, 28, 29, 29, 64, 64
      ]);
    
      const inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) =>
      {
        const bits = opts.bits;
            //here = opts.here; /* table entry for duplication */
    
        let len = 0;               /* a code's length in bits */
        let sym = 0;               /* index of code symbols */
        let min = 0, max = 0;          /* minimum and maximum code lengths */
        let root = 0;              /* number of index bits for root table */
        let curr = 0;              /* number of index bits for current table */
        let drop = 0;              /* code bits to drop for sub-table */
        let left = 0;                   /* number of prefix codes available */
        let used = 0;              /* code entries in table used */
        let huff = 0;              /* Huffman code */
        let incr;              /* for incrementing code, index */
        let fill;              /* index for replicating entries */
        let low;               /* low bits for current root entry */
        let mask;              /* mask for low root bits */
        let next;             /* next available space in table */
        let base = null;     /* base value table to use */
      //  let shoextra;    /* extra bits table to use */
        let match;                  /* use base and extra for symbol >= match */
        const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1];    /* number of codes of each length */
        const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1];     /* offsets in table for each length */
        let extra = null;
    
        let here_bits, here_op, here_val;
    
        /*
         Process a set of code lengths to create a canonical Huffman code.  The
         code lengths are lens[0..codes-1].  Each length corresponds to the
         symbols 0..codes-1.  The Huffman code is generated by first sorting the
         symbols by length from short to long, and retaining the symbol order
         for codes with equal lengths.  Then the code starts with all zero bits
         for the first code of the shortest length, and the codes are integer
         increments for the same length, and zeros are appended as the length
         increases.  For the deflate format, these bits are stored backwards
         from their more natural integer increment ordering, and so when the
         decoding tables are built in the large loop below, the integer codes
         are incremented backwards.
    
         This routine assumes, but does not check, that all of the entries in
         lens[] are in the range 0..MAXBITS.  The caller must assure this.
         1..MAXBITS is interpreted as that code length.  zero means that that
         symbol does not occur in this code.
    
         The codes are sorted by computing a count of codes for each length,
         creating from that a table of starting indices for each length in the
         sorted table, and then entering the symbols in order in the sorted
         table.  The sorted table is work[], with that space being provided by
         the caller.
    
         The length counts are used for other purposes as well, i.e. finding
         the minimum and maximum length codes, determining if there are any
         codes at all, checking for a valid set of lengths, and looking ahead
         at length counts to determine sub-table sizes when building the
         decoding tables.
         */
    
        /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
        for (len = 0; len <= MAXBITS; len++) {
          count[len] = 0;
        }
        for (sym = 0; sym < codes; sym++) {
          count[lens[lens_index + sym]]++;
        }
    
        /* bound code lengths, force root to be within code lengths */
        root = bits;
        for (max = MAXBITS; max >= 1; max--) {
          if (count[max] !== 0) { break; }
        }
        if (root > max) {
          root = max;
        }
        if (max === 0) {                     /* no symbols to code at all */
          //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */
          //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;
          //table.val[opts.table_index++] = 0;   //here.val = (var short)0;
          table[table_index++] = (1 << 24) | (64 << 16) | 0;
    
    
          //table.op[opts.table_index] = 64;
          //table.bits[opts.table_index] = 1;
          //table.val[opts.table_index++] = 0;
          table[table_index++] = (1 << 24) | (64 << 16) | 0;
    
          opts.bits = 1;
          return 0;     /* no symbols, but wait for decoding to report error */
        }
        for (min = 1; min < max; min++) {
          if (count[min] !== 0) { break; }
        }
        if (root < min) {
          root = min;
        }
    
        /* check for an over-subscribed or incomplete set of lengths */
        left = 1;
        for (len = 1; len <= MAXBITS; len++) {
          left <<= 1;
          left -= count[len];
          if (left < 0) {
            return -1;
          }        /* over-subscribed */
        }
        if (left > 0 && (type === CODES$1 || max !== 1)) {
          return -1;                      /* incomplete set */
        }
    
        /* generate offsets into symbol table for each length for sorting */
        offs[1] = 0;
        for (len = 1; len < MAXBITS; len++) {
          offs[len + 1] = offs[len] + count[len];
        }
    
        /* sort symbols by length, by symbol order within each length */
        for (sym = 0; sym < codes; sym++) {
          if (lens[lens_index + sym] !== 0) {
            work[offs[lens[lens_index + sym]]++] = sym;
          }
        }
    
        /*
         Create and fill in decoding tables.  In this loop, the table being
         filled is at next and has curr index bits.  The code being used is huff
         with length len.  That code is converted to an index by dropping drop
         bits off of the bottom.  For codes where len is less than drop + curr,
         those top drop + curr - len bits are incremented through all values to
         fill the table with replicated entries.
    
         root is the number of index bits for the root table.  When len exceeds
         root, sub-tables are created pointed to by the root entry with an index
         of the low root bits of huff.  This is saved in low to check for when a
         new sub-table should be started.  drop is zero when the root table is
         being filled, and drop is root when sub-tables are being filled.
    
         When a new sub-table is needed, it is necessary to look ahead in the
         code lengths to determine what size sub-table is needed.  The length
         counts are used for this, and so count[] is decremented as codes are
         entered in the tables.
    
         used keeps track of how many table entries have been allocated from the
         provided *table space.  It is checked for LENS and DIST tables against
         the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
         the initial root table size constants.  See the comments in inftrees.h
         for more information.
    
         sym increments through all symbols, and the loop terminates when
         all codes of length max, i.e. all codes, have been processed.  This
         routine permits incomplete codes, so another loop after this one fills
         in the rest of the decoding tables with invalid code markers.
         */
    
        /* set up for code type */
        // poor man optimization - use if-else instead of switch,
        // to avoid deopts in old v8
        if (type === CODES$1) {
          base = extra = work;    /* dummy value--not used */
          match = 20;
    
        } else if (type === LENS$1) {
          base = lbase;
          extra = lext;
          match = 257;
    
        } else {                    /* DISTS */
          base = dbase;
          extra = dext;
          match = 0;
        }
    
        /* initialize opts for loop */
        huff = 0;                   /* starting code */
        sym = 0;                    /* starting code symbol */
        len = min;                  /* starting code length */
        next = table_index;              /* current table to fill in */
        curr = root;                /* current table index bits */
        drop = 0;                   /* current bits to drop from code for index */
        low = -1;                   /* trigger new sub-table when len > root */
        used = 1 << root;          /* use root table entries */
        mask = used - 1;            /* mask for comparing low */
    
        /* check available table space */
        if ((type === LENS$1 && used > ENOUGH_LENS$1) ||
          (type === DISTS$1 && used > ENOUGH_DISTS$1)) {
          return 1;
        }
    
        /* process all codes and make table entries */
        for (;;) {
          /* create table entry */
          here_bits = len - drop;
          if (work[sym] + 1 < match) {
            here_op = 0;
            here_val = work[sym];
          }
          else if (work[sym] >= match) {
            here_op = extra[work[sym] - match];
            here_val = base[work[sym] - match];
          }
          else {
            here_op = 32 + 64;         /* end of block */
            here_val = 0;
          }
    
          /* replicate for those indices with low len bits equal to huff */
          incr = 1 << (len - drop);
          fill = 1 << curr;
          min = fill;                 /* save offset to next table */
          do {
            fill -= incr;
            table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
          } while (fill !== 0);
    
          /* backwards increment the len-bit code huff */
          incr = 1 << (len - 1);
          while (huff & incr) {
            incr >>= 1;
          }
          if (incr !== 0) {
            huff &= incr - 1;
            huff += incr;
          } else {
            huff = 0;
          }
    
          /* go to next symbol, update count, len */
          sym++;
          if (--count[len] === 0) {
            if (len === max) { break; }
            len = lens[lens_index + work[sym]];
          }
    
          /* create new sub-table if needed */
          if (len > root && (huff & mask) !== low) {
            /* if first time, transition to sub-tables */
            if (drop === 0) {
              drop = root;
            }
    
            /* increment past last table */
            next += min;            /* here min is 1 << curr */
    
            /* determine length of next table */
            curr = len - drop;
            left = 1 << curr;
            while (curr + drop < max) {
              left -= count[curr + drop];
              if (left <= 0) { break; }
              curr++;
              left <<= 1;
            }
    
            /* check for enough space */
            used += 1 << curr;
            if ((type === LENS$1 && used > ENOUGH_LENS$1) ||
              (type === DISTS$1 && used > ENOUGH_DISTS$1)) {
              return 1;
            }
    
            /* point entry in root table to sub-table */
            low = huff & mask;
            /*table.op[low] = curr;
            table.bits[low] = root;
            table.val[low] = next - opts.table_index;*/
            table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
          }
        }
    
        /* fill in remaining table entry if code is incomplete (guaranteed to have
         at most one remaining entry, since if the code is incomplete, the
         maximum code length that was allowed to get this far is one bit) */
        if (huff !== 0) {
          //table.op[next + huff] = 64;            /* invalid code marker */
          //table.bits[next + huff] = len - drop;
          //table.val[next + huff] = 0;
          table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
        }
    
        /* set return parameters */
        //opts.table_index += used;
        opts.bits = root;
        return 0;
      };
    
    
      var inftrees = inflate_table;
    
      // (C) 1995-2013 Jean-loup Gailly and Mark Adler
      // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
      //
      // This software is provided 'as-is', without any express or implied
      // warranty. In no event will the authors be held liable for any damages
      // arising from the use of this software.
      //
      // Permission is granted to anyone to use this software for any purpose,
      // including commercial applications, and to alter it and redistribute it
      // freely, subject to the following restrictions:
      //
      // 1. The origin of this software must not be misrepresented; you must not
      //   claim that you wrote the original software. If you use this software
      //   in a product, an acknowledgment in the product documentation would be
      //   appreciated but is not required.
      // 2. Altered source versions must be plainly marked as such, and must not be
      //   misrepresented as being the original software.
      // 3. This notice may not be removed or altered from any source distribution.
    
    
    
    
    
    
      const CODES = 0;
      const LENS = 1;
      const DISTS = 2;
    
      /* Public constants ==========================================================*/
      /* ===========================================================================*/
    
      const {
        Z_FINISH: Z_FINISH$1, Z_BLOCK, Z_TREES,
        Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1, Z_NEED_DICT: Z_NEED_DICT$1, Z_STREAM_ERROR: Z_STREAM_ERROR$1, Z_DATA_ERROR: Z_DATA_ERROR$1, Z_MEM_ERROR: Z_MEM_ERROR$1, Z_BUF_ERROR,
        Z_DEFLATED
      } = constants$2;
    
    
      /* STATES ====================================================================*/
      /* ===========================================================================*/
    
    
      const    HEAD = 16180;       /* i: waiting for magic header */
      const    FLAGS = 16181;      /* i: waiting for method and flags (gzip) */
      const    TIME = 16182;       /* i: waiting for modification time (gzip) */
      const    OS = 16183;         /* i: waiting for extra flags and operating system (gzip) */
      const    EXLEN = 16184;      /* i: waiting for extra length (gzip) */
      const    EXTRA = 16185;      /* i: waiting for extra bytes (gzip) */
      const    NAME = 16186;       /* i: waiting for end of file name (gzip) */
      const    COMMENT = 16187;    /* i: waiting for end of comment (gzip) */
      const    HCRC = 16188;       /* i: waiting for header crc (gzip) */
      const    DICTID = 16189;    /* i: waiting for dictionary check value */
      const    DICT = 16190;      /* waiting for inflateSetDictionary() call */
      const        TYPE = 16191;      /* i: waiting for type bits, including last-flag bit */
      const        TYPEDO = 16192;    /* i: same, but skip check to exit inflate on new block */
      const        STORED = 16193;    /* i: waiting for stored size (length and complement) */
      const        COPY_ = 16194;     /* i/o: same as COPY below, but only first time in */
      const        COPY = 16195;      /* i/o: waiting for input or output to copy stored block */
      const        TABLE = 16196;     /* i: waiting for dynamic block table lengths */
      const        LENLENS = 16197;   /* i: waiting for code length code lengths */
      const        CODELENS = 16198;  /* i: waiting for length/lit and distance code lengths */
      const            LEN_ = 16199;      /* i: same as LEN below, but only first time in */
      const            LEN = 16200;       /* i: waiting for length/lit/eob code */
      const            LENEXT = 16201;    /* i: waiting for length extra bits */
      const            DIST = 16202;      /* i: waiting for distance code */
      const            DISTEXT = 16203;   /* i: waiting for distance extra bits */
      const            MATCH = 16204;     /* o: waiting for output space to copy string */
      const            LIT = 16205;       /* o: waiting for output space to write literal */
      const    CHECK = 16206;     /* i: waiting for 32-bit check value */
      const    LENGTH = 16207;    /* i: waiting for 32-bit length (gzip) */
      const    DONE = 16208;      /* finished check, done -- remain here until reset */
      const    BAD = 16209;       /* got a data error -- remain here until reset */
      const    MEM = 16210;       /* got an inflate() memory error -- remain here until reset */
      const    SYNC = 16211;      /* looking for synchronization bytes to restart inflate() */
    
      /* ===========================================================================*/
    
    
    
      const ENOUGH_LENS = 852;
      const ENOUGH_DISTS = 592;
      //const ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);
    
      const MAX_WBITS = 15;
      /* 32K LZ77 window */
      const DEF_WBITS = MAX_WBITS;
    
    
      const zswap32 = (q) => {
    
        return  (((q >>> 24) & 0xff) +
                ((q >>> 8) & 0xff00) +
                ((q & 0xff00) << 8) +
                ((q & 0xff) << 24));
      };
    
    
      function InflateState() {
        this.strm = null;           /* pointer back to this zlib stream */
        this.mode = 0;              /* current inflate mode */
        this.last = false;          /* true if processing last block */
        this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip,
                                       bit 2 true to validate check value */
        this.havedict = false;      /* true if dictionary provided */
        this.flags = 0;             /* gzip header method and flags (0 if zlib), or
                                       -1 if raw or no header yet */
        this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */
        this.check = 0;             /* protected copy of check value */
        this.total = 0;             /* protected copy of output count */
        // TODO: may be {}
        this.head = null;           /* where to save gzip header information */
    
        /* sliding window */
        this.wbits = 0;             /* log base 2 of requested window size */
        this.wsize = 0;             /* window size or zero if not using window */
        this.whave = 0;             /* valid bytes in the window */
        this.wnext = 0;             /* window write index */
        this.window = null;         /* allocated sliding window, if needed */
    
        /* bit accumulator */
        this.hold = 0;              /* input bit accumulator */
        this.bits = 0;              /* number of bits in "in" */
    
        /* for string and stored block copying */
        this.length = 0;            /* literal or length of data to copy */
        this.offset = 0;            /* distance back to copy string from */
    
        /* for table and code decoding */
        this.extra = 0;             /* extra bits needed */
    
        /* fixed and dynamic code tables */
        this.lencode = null;          /* starting table for length/literal codes */
        this.distcode = null;         /* starting table for distance codes */
        this.lenbits = 0;           /* index bits for lencode */
        this.distbits = 0;          /* index bits for distcode */
    
        /* dynamic table building */
        this.ncode = 0;             /* number of code length code lengths */
        this.nlen = 0;              /* number of length code lengths */
        this.ndist = 0;             /* number of distance code lengths */
        this.have = 0;              /* number of code lengths in lens[] */
        this.next = null;              /* next available space in codes[] */
    
        this.lens = new Uint16Array(320); /* temporary storage for code lengths */
        this.work = new Uint16Array(288); /* work area for code table building */
    
        /*
         because we don't have pointers in js, we use lencode and distcode directly
         as buffers so we don't need codes
        */
        //this.codes = new Int32Array(ENOUGH);       /* space for code tables */
        this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */
        this.distdyn = null;             /* dynamic table for distance codes (JS specific) */
        this.sane = 0;                   /* if false, allow invalid distance too far */
        this.back = 0;                   /* bits back of last unprocessed length/lit */
        this.was = 0;                    /* initial length of match */
      }
    
    
      const inflateStateCheck = (strm) => {
    
        if (!strm) {
          return 1;
        }
        const state = strm.state;
        if (!state || state.strm !== strm ||
          state.mode < HEAD || state.mode > SYNC) {
          return 1;
        }
        return 0;
      };
    
    
      const inflateResetKeep = (strm) => {
    
        if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }
        const state = strm.state;
        strm.total_in = strm.total_out = state.total = 0;
        strm.msg = ''; /*Z_NULL*/
        if (state.wrap) {       /* to support ill-conceived Java test suite */
          strm.adler = state.wrap & 1;
        }
        state.mode = HEAD;
        state.last = 0;
        state.havedict = 0;
        state.flags = -1;
        state.dmax = 32768;
        state.head = null/*Z_NULL*/;
        state.hold = 0;
        state.bits = 0;
        //state.lencode = state.distcode = state.next = state.codes;
        state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS);
        state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS);
    
        state.sane = 1;
        state.back = -1;
        //Tracev((stderr, "inflate: reset\n"));
        return Z_OK$1;
      };
    
    
      const inflateReset = (strm) => {
    
        if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }
        const state = strm.state;
        state.wsize = 0;
        state.whave = 0;
        state.wnext = 0;
        return inflateResetKeep(strm);
    
      };
    
    
      const inflateReset2 = (strm, windowBits) => {
        let wrap;
    
        /* get the state */
        if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }
        const state = strm.state;
    
        /* extract wrap request from windowBits parameter */
        if (windowBits < 0) {
          wrap = 0;
          windowBits = -windowBits;
        }
        else {
          wrap = (windowBits >> 4) + 5;
          if (windowBits < 48) {
            windowBits &= 15;
          }
        }
    
        /* set number of window bits, free window if different */
        if (windowBits && (windowBits < 8 || windowBits > 15)) {
          return Z_STREAM_ERROR$1;
        }
        if (state.window !== null && state.wbits !== windowBits) {
          state.window = null;
        }
    
        /* update state and reset the rest of it */
        state.wrap = wrap;
        state.wbits = windowBits;
        return inflateReset(strm);
      };
    
    
      const inflateInit2 = (strm, windowBits) => {
    
        if (!strm) { return Z_STREAM_ERROR$1; }
        //strm.msg = Z_NULL;                 /* in case we return an error */
    
        const state = new InflateState();
    
        //if (state === Z_NULL) return Z_MEM_ERROR;
        //Tracev((stderr, "inflate: allocated\n"));
        strm.state = state;
        state.strm = strm;
        state.window = null/*Z_NULL*/;
        state.mode = HEAD;     /* to pass state test in inflateReset2() */
        const ret = inflateReset2(strm, windowBits);
        if (ret !== Z_OK$1) {
          strm.state = null/*Z_NULL*/;
        }
        return ret;
      };
    
    
      const inflateInit = (strm) => {
    
        return inflateInit2(strm, DEF_WBITS);
      };
    
    
      /*
       Return state with length and distance decoding tables and index sizes set to
       fixed code decoding.  Normally this returns fixed tables from inffixed.h.
       If BUILDFIXED is defined, then instead this routine builds the tables the
       first time it's called, and returns those tables the first time and
       thereafter.  This reduces the size of the code by about 2K bytes, in
       exchange for a little execution time.  However, BUILDFIXED should not be
       used for threaded applications, since the rewriting of the tables and virgin
       may not be thread-safe.
       */
      let virgin = true;
    
      let lenfix, distfix; // We have no pointers in JS, so keep tables separate
    
    
      const fixedtables = (state) => {
    
        /* build fixed huffman tables if first call (may not be thread safe) */
        if (virgin) {
          lenfix = new Int32Array(512);
          distfix = new Int32Array(32);
    
          /* literal/length table */
          let sym = 0;
          while (sym < 144) { state.lens[sym++] = 8; }
          while (sym < 256) { state.lens[sym++] = 9; }
          while (sym < 280) { state.lens[sym++] = 7; }
          while (sym < 288) { state.lens[sym++] = 8; }
    
          inftrees(LENS,  state.lens, 0, 288, lenfix,   0, state.work, { bits: 9 });
    
          /* distance table */
          sym = 0;
          while (sym < 32) { state.lens[sym++] = 5; }
    
          inftrees(DISTS, state.lens, 0, 32,   distfix, 0, state.work, { bits: 5 });
    
          /* do this just once */
          virgin = false;
        }
    
        state.lencode = lenfix;
        state.lenbits = 9;
        state.distcode = distfix;
        state.distbits = 5;
      };
    
    
      /*
       Update the window with the last wsize (normally 32K) bytes written before
       returning.  If window does not exist yet, create it.  This is only called
       when a window is already in use, or when output has been written during this
       inflate call, but the end of the deflate stream has not been reached yet.
       It is also called to create a window for dictionary data when a dictionary
       is loaded.
    
       Providing output buffers larger than 32K to inflate() should provide a speed
       advantage, since only the last 32K of output is copied to the sliding window
       upon return from inflate(), and since all distances after the first 32K of
       output will fall in the output data, making match copies simpler and faster.
       The advantage may be dependent on the size of the processor's data caches.
       */
      const updatewindow = (strm, src, end, copy) => {
    
        let dist;
        const state = strm.state;
    
        /* if it hasn't been done already, allocate space for the window */
        if (state.window === null) {
          state.wsize = 1 << state.wbits;
          state.wnext = 0;
          state.whave = 0;
    
          state.window = new Uint8Array(state.wsize);
        }
    
        /* copy state->wsize or less output bytes into the circular window */
        if (copy >= state.wsize) {
          state.window.set(src.subarray(end - state.wsize, end), 0);
          state.wnext = 0;
          state.whave = state.wsize;
        }
        else {
          dist = state.wsize - state.wnext;
          if (dist > copy) {
            dist = copy;
          }
          //zmemcpy(state->window + state->wnext, end - copy, dist);
          state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext);
          copy -= dist;
          if (copy) {
            //zmemcpy(state->window, end - copy, copy);
            state.window.set(src.subarray(end - copy, end), 0);
            state.wnext = copy;
            state.whave = state.wsize;
          }
          else {
            state.wnext += dist;
            if (state.wnext === state.wsize) { state.wnext = 0; }
            if (state.whave < state.wsize) { state.whave += dist; }
          }
        }
        return 0;
      };
    
    
      const inflate$2 = (strm, flush) => {
    
        let state;
        let input, output;          // input/output buffers
        let next;                   /* next input INDEX */
        let put;                    /* next output INDEX */
        let have, left;             /* available input and output */
        let hold;                   /* bit buffer */
        let bits;                   /* bits in bit buffer */
        let _in, _out;              /* save starting available input and output */
        let copy;                   /* number of stored or match bytes to copy */
        let from;                   /* where to copy match bytes from */
        let from_source;
        let here = 0;               /* current decoding table entry */
        let here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
        //let last;                   /* parent table entry */
        let last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
        let len;                    /* length to copy for repeats, bits to drop */
        let ret;                    /* return code */
        const hbuf = new Uint8Array(4);    /* buffer for gzip header crc calculation */
        let opts;
    
        let n; // temporary variable for NEED_BITS
    
        const order = /* permutation of code lengths */
          new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]);
    
    
        if (inflateStateCheck(strm) || !strm.output ||
            (!strm.input && strm.avail_in !== 0)) {
          return Z_STREAM_ERROR$1;
        }
    
        state = strm.state;
        if (state.mode === TYPE) { state.mode = TYPEDO; }    /* skip check */
    
    
        //--- LOAD() ---
        put = strm.next_out;
        output = strm.output;
        left = strm.avail_out;
        next = strm.next_in;
        input = strm.input;
        have = strm.avail_in;
        hold = state.hold;
        bits = state.bits;
        //---
    
        _in = have;
        _out = left;
        ret = Z_OK$1;
    
        inf_leave: // goto emulation
        for (;;) {
          switch (state.mode) {
            case HEAD:
              if (state.wrap === 0) {
                state.mode = TYPEDO;
                break;
              }
              //=== NEEDBITS(16);
              while (bits < 16) {
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              //===//
              if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */
                if (state.wbits === 0) {
                  state.wbits = 15;
                }
                state.check = 0/*crc32(0L, Z_NULL, 0)*/;
                //=== CRC2(state.check, hold);
                hbuf[0] = hold & 0xff;
                hbuf[1] = (hold >>> 8) & 0xff;
                state.check = crc32_1(state.check, hbuf, 2, 0);
                //===//
    
                //=== INITBITS();
                hold = 0;
                bits = 0;
                //===//
                state.mode = FLAGS;
                break;
              }
              if (state.head) {
                state.head.done = false;
              }
              if (!(state.wrap & 1) ||   /* check if zlib header allowed */
                (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
                strm.msg = 'incorrect header check';
                state.mode = BAD;
                break;
              }
              if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
                strm.msg = 'unknown compression method';
                state.mode = BAD;
                break;
              }
              //--- DROPBITS(4) ---//
              hold >>>= 4;
              bits -= 4;
              //---//
              len = (hold & 0x0f)/*BITS(4)*/ + 8;
              if (state.wbits === 0) {
                state.wbits = len;
              }
              if (len > 15 || len > state.wbits) {
                strm.msg = 'invalid window size';
                state.mode = BAD;
                break;
              }
    
              // !!! pako patch. Force use `options.windowBits` if passed.
              // Required to always use max window size by default.
              state.dmax = 1 << state.wbits;
              //state.dmax = 1 << len;
    
              state.flags = 0;               /* indicate zlib header */
              //Tracev((stderr, "inflate:   zlib header ok\n"));
              strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
              state.mode = hold & 0x200 ? DICTID : TYPE;
              //=== INITBITS();
              hold = 0;
              bits = 0;
              //===//
              break;
            case FLAGS:
              //=== NEEDBITS(16); */
              while (bits < 16) {
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              //===//
              state.flags = hold;
              if ((state.flags & 0xff) !== Z_DEFLATED) {
                strm.msg = 'unknown compression method';
                state.mode = BAD;
                break;
              }
              if (state.flags & 0xe000) {
                strm.msg = 'unknown header flags set';
                state.mode = BAD;
                break;
              }
              if (state.head) {
                state.head.text = ((hold >> 8) & 1);
              }
              if ((state.flags & 0x0200) && (state.wrap & 4)) {
                //=== CRC2(state.check, hold);
                hbuf[0] = hold & 0xff;
                hbuf[1] = (hold >>> 8) & 0xff;
                state.check = crc32_1(state.check, hbuf, 2, 0);
                //===//
              }
              //=== INITBITS();
              hold = 0;
              bits = 0;
              //===//
              state.mode = TIME;
              /* falls through */
            case TIME:
              //=== NEEDBITS(32); */
              while (bits < 32) {
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              //===//
              if (state.head) {
                state.head.time = hold;
              }
              if ((state.flags & 0x0200) && (state.wrap & 4)) {
                //=== CRC4(state.check, hold)
                hbuf[0] = hold & 0xff;
                hbuf[1] = (hold >>> 8) & 0xff;
                hbuf[2] = (hold >>> 16) & 0xff;
                hbuf[3] = (hold >>> 24) & 0xff;
                state.check = crc32_1(state.check, hbuf, 4, 0);
                //===
              }
              //=== INITBITS();
              hold = 0;
              bits = 0;
              //===//
              state.mode = OS;
              /* falls through */
            case OS:
              //=== NEEDBITS(16); */
              while (bits < 16) {
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              //===//
              if (state.head) {
                state.head.xflags = (hold & 0xff);
                state.head.os = (hold >> 8);
              }
              if ((state.flags & 0x0200) && (state.wrap & 4)) {
                //=== CRC2(state.check, hold);
                hbuf[0] = hold & 0xff;
                hbuf[1] = (hold >>> 8) & 0xff;
                state.check = crc32_1(state.check, hbuf, 2, 0);
                //===//
              }
              //=== INITBITS();
              hold = 0;
              bits = 0;
              //===//
              state.mode = EXLEN;
              /* falls through */
            case EXLEN:
              if (state.flags & 0x0400) {
                //=== NEEDBITS(16); */
                while (bits < 16) {
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                //===//
                state.length = hold;
                if (state.head) {
                  state.head.extra_len = hold;
                }
                if ((state.flags & 0x0200) && (state.wrap & 4)) {
                  //=== CRC2(state.check, hold);
                  hbuf[0] = hold & 0xff;
                  hbuf[1] = (hold >>> 8) & 0xff;
                  state.check = crc32_1(state.check, hbuf, 2, 0);
                  //===//
                }
                //=== INITBITS();
                hold = 0;
                bits = 0;
                //===//
              }
              else if (state.head) {
                state.head.extra = null/*Z_NULL*/;
              }
              state.mode = EXTRA;
              /* falls through */
            case EXTRA:
              if (state.flags & 0x0400) {
                copy = state.length;
                if (copy > have) { copy = have; }
                if (copy) {
                  if (state.head) {
                    len = state.head.extra_len - state.length;
                    if (!state.head.extra) {
                      // Use untyped array for more convenient processing later
                      state.head.extra = new Uint8Array(state.head.extra_len);
                    }
                    state.head.extra.set(
                      input.subarray(
                        next,
                        // extra field is limited to 65536 bytes
                        // - no need for additional size check
                        next + copy
                      ),
                      /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
                      len
                    );
                    //zmemcpy(state.head.extra + len, next,
                    //        len + copy > state.head.extra_max ?
                    //        state.head.extra_max - len : copy);
                  }
                  if ((state.flags & 0x0200) && (state.wrap & 4)) {
                    state.check = crc32_1(state.check, input, copy, next);
                  }
                  have -= copy;
                  next += copy;
                  state.length -= copy;
                }
                if (state.length) { break inf_leave; }
              }
              state.length = 0;
              state.mode = NAME;
              /* falls through */
            case NAME:
              if (state.flags & 0x0800) {
                if (have === 0) { break inf_leave; }
                copy = 0;
                do {
                  // TODO: 2 or 1 bytes?
                  len = input[next + copy++];
                  /* use constant limit because in js we should not preallocate memory */
                  if (state.head && len &&
                      (state.length < 65536 /*state.head.name_max*/)) {
                    state.head.name += String.fromCharCode(len);
                  }
                } while (len && copy < have);
    
                if ((state.flags & 0x0200) && (state.wrap & 4)) {
                  state.check = crc32_1(state.check, input, copy, next);
                }
                have -= copy;
                next += copy;
                if (len) { break inf_leave; }
              }
              else if (state.head) {
                state.head.name = null;
              }
              state.length = 0;
              state.mode = COMMENT;
              /* falls through */
            case COMMENT:
              if (state.flags & 0x1000) {
                if (have === 0) { break inf_leave; }
                copy = 0;
                do {
                  len = input[next + copy++];
                  /* use constant limit because in js we should not preallocate memory */
                  if (state.head && len &&
                      (state.length < 65536 /*state.head.comm_max*/)) {
                    state.head.comment += String.fromCharCode(len);
                  }
                } while (len && copy < have);
                if ((state.flags & 0x0200) && (state.wrap & 4)) {
                  state.check = crc32_1(state.check, input, copy, next);
                }
                have -= copy;
                next += copy;
                if (len) { break inf_leave; }
              }
              else if (state.head) {
                state.head.comment = null;
              }
              state.mode = HCRC;
              /* falls through */
            case HCRC:
              if (state.flags & 0x0200) {
                //=== NEEDBITS(16); */
                while (bits < 16) {
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                //===//
                if ((state.wrap & 4) && hold !== (state.check & 0xffff)) {
                  strm.msg = 'header crc mismatch';
                  state.mode = BAD;
                  break;
                }
                //=== INITBITS();
                hold = 0;
                bits = 0;
                //===//
              }
              if (state.head) {
                state.head.hcrc = ((state.flags >> 9) & 1);
                state.head.done = true;
              }
              strm.adler = state.check = 0;
              state.mode = TYPE;
              break;
            case DICTID:
              //=== NEEDBITS(32); */
              while (bits < 32) {
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              //===//
              strm.adler = state.check = zswap32(hold);
              //=== INITBITS();
              hold = 0;
              bits = 0;
              //===//
              state.mode = DICT;
              /* falls through */
            case DICT:
              if (state.havedict === 0) {
                //--- RESTORE() ---
                strm.next_out = put;
                strm.avail_out = left;
                strm.next_in = next;
                strm.avail_in = have;
                state.hold = hold;
                state.bits = bits;
                //---
                return Z_NEED_DICT$1;
              }
              strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
              state.mode = TYPE;
              /* falls through */
            case TYPE:
              if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
              /* falls through */
            case TYPEDO:
              if (state.last) {
                //--- BYTEBITS() ---//
                hold >>>= bits & 7;
                bits -= bits & 7;
                //---//
                state.mode = CHECK;
                break;
              }
              //=== NEEDBITS(3); */
              while (bits < 3) {
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              //===//
              state.last = (hold & 0x01)/*BITS(1)*/;
              //--- DROPBITS(1) ---//
              hold >>>= 1;
              bits -= 1;
              //---//
    
              switch ((hold & 0x03)/*BITS(2)*/) {
                case 0:                             /* stored block */
                  //Tracev((stderr, "inflate:     stored block%s\n",
                  //        state.last ? " (last)" : ""));
                  state.mode = STORED;
                  break;
                case 1:                             /* fixed block */
                  fixedtables(state);
                  //Tracev((stderr, "inflate:     fixed codes block%s\n",
                  //        state.last ? " (last)" : ""));
                  state.mode = LEN_;             /* decode codes */
                  if (flush === Z_TREES) {
                    //--- DROPBITS(2) ---//
                    hold >>>= 2;
                    bits -= 2;
                    //---//
                    break inf_leave;
                  }
                  break;
                case 2:                             /* dynamic block */
                  //Tracev((stderr, "inflate:     dynamic codes block%s\n",
                  //        state.last ? " (last)" : ""));
                  state.mode = TABLE;
                  break;
                case 3:
                  strm.msg = 'invalid block type';
                  state.mode = BAD;
              }
              //--- DROPBITS(2) ---//
              hold >>>= 2;
              bits -= 2;
              //---//
              break;
            case STORED:
              //--- BYTEBITS() ---// /* go to byte boundary */
              hold >>>= bits & 7;
              bits -= bits & 7;
              //---//
              //=== NEEDBITS(32); */
              while (bits < 32) {
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              //===//
              if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
                strm.msg = 'invalid stored block lengths';
                state.mode = BAD;
                break;
              }
              state.length = hold & 0xffff;
              //Tracev((stderr, "inflate:       stored length %u\n",
              //        state.length));
              //=== INITBITS();
              hold = 0;
              bits = 0;
              //===//
              state.mode = COPY_;
              if (flush === Z_TREES) { break inf_leave; }
              /* falls through */
            case COPY_:
              state.mode = COPY;
              /* falls through */
            case COPY:
              copy = state.length;
              if (copy) {
                if (copy > have) { copy = have; }
                if (copy > left) { copy = left; }
                if (copy === 0) { break inf_leave; }
                //--- zmemcpy(put, next, copy); ---
                output.set(input.subarray(next, next + copy), put);
                //---//
                have -= copy;
                next += copy;
                left -= copy;
                put += copy;
                state.length -= copy;
                break;
              }
              //Tracev((stderr, "inflate:       stored end\n"));
              state.mode = TYPE;
              break;
            case TABLE:
              //=== NEEDBITS(14); */
              while (bits < 14) {
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              //===//
              state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
              //--- DROPBITS(5) ---//
              hold >>>= 5;
              bits -= 5;
              //---//
              state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
              //--- DROPBITS(5) ---//
              hold >>>= 5;
              bits -= 5;
              //---//
              state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
              //--- DROPBITS(4) ---//
              hold >>>= 4;
              bits -= 4;
              //---//
      //#ifndef PKZIP_BUG_WORKAROUND
              if (state.nlen > 286 || state.ndist > 30) {
                strm.msg = 'too many length or distance symbols';
                state.mode = BAD;
                break;
              }
      //#endif
              //Tracev((stderr, "inflate:       table sizes ok\n"));
              state.have = 0;
              state.mode = LENLENS;
              /* falls through */
            case LENLENS:
              while (state.have < state.ncode) {
                //=== NEEDBITS(3);
                while (bits < 3) {
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                //===//
                state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
                //--- DROPBITS(3) ---//
                hold >>>= 3;
                bits -= 3;
                //---//
              }
              while (state.have < 19) {
                state.lens[order[state.have++]] = 0;
              }
              // We have separate tables & no pointers. 2 commented lines below not needed.
              //state.next = state.codes;
              //state.lencode = state.next;
              // Switch to use dynamic table
              state.lencode = state.lendyn;
              state.lenbits = 7;
    
              opts = { bits: state.lenbits };
              ret = inftrees(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
              state.lenbits = opts.bits;
    
              if (ret) {
                strm.msg = 'invalid code lengths set';
                state.mode = BAD;
                break;
              }
              //Tracev((stderr, "inflate:       code lengths ok\n"));
              state.have = 0;
              state.mode = CODELENS;
              /* falls through */
            case CODELENS:
              while (state.have < state.nlen + state.ndist) {
                for (;;) {
                  here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
                  here_bits = here >>> 24;
                  here_op = (here >>> 16) & 0xff;
                  here_val = here & 0xffff;
    
                  if ((here_bits) <= bits) { break; }
                  //--- PULLBYTE() ---//
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                  //---//
                }
                if (here_val < 16) {
                  //--- DROPBITS(here.bits) ---//
                  hold >>>= here_bits;
                  bits -= here_bits;
                  //---//
                  state.lens[state.have++] = here_val;
                }
                else {
                  if (here_val === 16) {
                    //=== NEEDBITS(here.bits + 2);
                    n = here_bits + 2;
                    while (bits < n) {
                      if (have === 0) { break inf_leave; }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    //===//
                    //--- DROPBITS(here.bits) ---//
                    hold >>>= here_bits;
                    bits -= here_bits;
                    //---//
                    if (state.have === 0) {
                      strm.msg = 'invalid bit length repeat';
                      state.mode = BAD;
                      break;
                    }
                    len = state.lens[state.have - 1];
                    copy = 3 + (hold & 0x03);//BITS(2);
                    //--- DROPBITS(2) ---//
                    hold >>>= 2;
                    bits -= 2;
                    //---//
                  }
                  else if (here_val === 17) {
                    //=== NEEDBITS(here.bits + 3);
                    n = here_bits + 3;
                    while (bits < n) {
                      if (have === 0) { break inf_leave; }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    //===//
                    //--- DROPBITS(here.bits) ---//
                    hold >>>= here_bits;
                    bits -= here_bits;
                    //---//
                    len = 0;
                    copy = 3 + (hold & 0x07);//BITS(3);
                    //--- DROPBITS(3) ---//
                    hold >>>= 3;
                    bits -= 3;
                    //---//
                  }
                  else {
                    //=== NEEDBITS(here.bits + 7);
                    n = here_bits + 7;
                    while (bits < n) {
                      if (have === 0) { break inf_leave; }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    //===//
                    //--- DROPBITS(here.bits) ---//
                    hold >>>= here_bits;
                    bits -= here_bits;
                    //---//
                    len = 0;
                    copy = 11 + (hold & 0x7f);//BITS(7);
                    //--- DROPBITS(7) ---//
                    hold >>>= 7;
                    bits -= 7;
                    //---//
                  }
                  if (state.have + copy > state.nlen + state.ndist) {
                    strm.msg = 'invalid bit length repeat';
                    state.mode = BAD;
                    break;
                  }
                  while (copy--) {
                    state.lens[state.have++] = len;
                  }
                }
              }
    
              /* handle error breaks in while */
              if (state.mode === BAD) { break; }
    
              /* check for end-of-block code (better have one) */
              if (state.lens[256] === 0) {
                strm.msg = 'invalid code -- missing end-of-block';
                state.mode = BAD;
                break;
              }
    
              /* build code tables -- note: do not change the lenbits or distbits
                 values here (9 and 6) without reading the comments in inftrees.h
                 concerning the ENOUGH constants, which depend on those values */
              state.lenbits = 9;
    
              opts = { bits: state.lenbits };
              ret = inftrees(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
              // We have separate tables & no pointers. 2 commented lines below not needed.
              // state.next_index = opts.table_index;
              state.lenbits = opts.bits;
              // state.lencode = state.next;
    
              if (ret) {
                strm.msg = 'invalid literal/lengths set';
                state.mode = BAD;
                break;
              }
    
              state.distbits = 6;
              //state.distcode.copy(state.codes);
              // Switch to use dynamic table
              state.distcode = state.distdyn;
              opts = { bits: state.distbits };
              ret = inftrees(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
              // We have separate tables & no pointers. 2 commented lines below not needed.
              // state.next_index = opts.table_index;
              state.distbits = opts.bits;
              // state.distcode = state.next;
    
              if (ret) {
                strm.msg = 'invalid distances set';
                state.mode = BAD;
                break;
              }
              //Tracev((stderr, 'inflate:       codes ok\n'));
              state.mode = LEN_;
              if (flush === Z_TREES) { break inf_leave; }
              /* falls through */
            case LEN_:
              state.mode = LEN;
              /* falls through */
            case LEN:
              if (have >= 6 && left >= 258) {
                //--- RESTORE() ---
                strm.next_out = put;
                strm.avail_out = left;
                strm.next_in = next;
                strm.avail_in = have;
                state.hold = hold;
                state.bits = bits;
                //---
                inffast(strm, _out);
                //--- LOAD() ---
                put = strm.next_out;
                output = strm.output;
                left = strm.avail_out;
                next = strm.next_in;
                input = strm.input;
                have = strm.avail_in;
                hold = state.hold;
                bits = state.bits;
                //---
    
                if (state.mode === TYPE) {
                  state.back = -1;
                }
                break;
              }
              state.back = 0;
              for (;;) {
                here = state.lencode[hold & ((1 << state.lenbits) - 1)];  /*BITS(state.lenbits)*/
                here_bits = here >>> 24;
                here_op = (here >>> 16) & 0xff;
                here_val = here & 0xffff;
    
                if (here_bits <= bits) { break; }
                //--- PULLBYTE() ---//
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
                //---//
              }
              if (here_op && (here_op & 0xf0) === 0) {
                last_bits = here_bits;
                last_op = here_op;
                last_val = here_val;
                for (;;) {
                  here = state.lencode[last_val +
                          ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
                  here_bits = here >>> 24;
                  here_op = (here >>> 16) & 0xff;
                  here_val = here & 0xffff;
    
                  if ((last_bits + here_bits) <= bits) { break; }
                  //--- PULLBYTE() ---//
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                  //---//
                }
                //--- DROPBITS(last.bits) ---//
                hold >>>= last_bits;
                bits -= last_bits;
                //---//
                state.back += last_bits;
              }
              //--- DROPBITS(here.bits) ---//
              hold >>>= here_bits;
              bits -= here_bits;
              //---//
              state.back += here_bits;
              state.length = here_val;
              if (here_op === 0) {
                //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
                //        "inflate:         literal '%c'\n" :
                //        "inflate:         literal 0x%02x\n", here.val));
                state.mode = LIT;
                break;
              }
              if (here_op & 32) {
                //Tracevv((stderr, "inflate:         end of block\n"));
                state.back = -1;
                state.mode = TYPE;
                break;
              }
              if (here_op & 64) {
                strm.msg = 'invalid literal/length code';
                state.mode = BAD;
                break;
              }
              state.extra = here_op & 15;
              state.mode = LENEXT;
              /* falls through */
            case LENEXT:
              if (state.extra) {
                //=== NEEDBITS(state.extra);
                n = state.extra;
                while (bits < n) {
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                //===//
                state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
                //--- DROPBITS(state.extra) ---//
                hold >>>= state.extra;
                bits -= state.extra;
                //---//
                state.back += state.extra;
              }
              //Tracevv((stderr, "inflate:         length %u\n", state.length));
              state.was = state.length;
              state.mode = DIST;
              /* falls through */
            case DIST:
              for (;;) {
                here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
                here_bits = here >>> 24;
                here_op = (here >>> 16) & 0xff;
                here_val = here & 0xffff;
    
                if ((here_bits) <= bits) { break; }
                //--- PULLBYTE() ---//
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
                //---//
              }
              if ((here_op & 0xf0) === 0) {
                last_bits = here_bits;
                last_op = here_op;
                last_val = here_val;
                for (;;) {
                  here = state.distcode[last_val +
                          ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
                  here_bits = here >>> 24;
                  here_op = (here >>> 16) & 0xff;
                  here_val = here & 0xffff;
    
                  if ((last_bits + here_bits) <= bits) { break; }
                  //--- PULLBYTE() ---//
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                  //---//
                }
                //--- DROPBITS(last.bits) ---//
                hold >>>= last_bits;
                bits -= last_bits;
                //---//
                state.back += last_bits;
              }
              //--- DROPBITS(here.bits) ---//
              hold >>>= here_bits;
              bits -= here_bits;
              //---//
              state.back += here_bits;
              if (here_op & 64) {
                strm.msg = 'invalid distance code';
                state.mode = BAD;
                break;
              }
              state.offset = here_val;
              state.extra = (here_op) & 15;
              state.mode = DISTEXT;
              /* falls through */
            case DISTEXT:
              if (state.extra) {
                //=== NEEDBITS(state.extra);
                n = state.extra;
                while (bits < n) {
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                //===//
                state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
                //--- DROPBITS(state.extra) ---//
                hold >>>= state.extra;
                bits -= state.extra;
                //---//
                state.back += state.extra;
              }
      //#ifdef INFLATE_STRICT
              if (state.offset > state.dmax) {
                strm.msg = 'invalid distance too far back';
                state.mode = BAD;
                break;
              }
      //#endif
              //Tracevv((stderr, "inflate:         distance %u\n", state.offset));
              state.mode = MATCH;
              /* falls through */
            case MATCH:
              if (left === 0) { break inf_leave; }
              copy = _out - left;
              if (state.offset > copy) {         /* copy from window */
                copy = state.offset - copy;
                if (copy > state.whave) {
                  if (state.sane) {
                    strm.msg = 'invalid distance too far back';
                    state.mode = BAD;
                    break;
                  }
      // (!) This block is disabled in zlib defaults,
      // don't enable it for binary compatibility
      //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
      //          Trace((stderr, "inflate.c too far\n"));
      //          copy -= state.whave;
      //          if (copy > state.length) { copy = state.length; }
      //          if (copy > left) { copy = left; }
      //          left -= copy;
      //          state.length -= copy;
      //          do {
      //            output[put++] = 0;
      //          } while (--copy);
      //          if (state.length === 0) { state.mode = LEN; }
      //          break;
      //#endif
                }
                if (copy > state.wnext) {
                  copy -= state.wnext;
                  from = state.wsize - copy;
                }
                else {
                  from = state.wnext - copy;
                }
                if (copy > state.length) { copy = state.length; }
                from_source = state.window;
              }
              else {                              /* copy from output */
                from_source = output;
                from = put - state.offset;
                copy = state.length;
              }
              if (copy > left) { copy = left; }
              left -= copy;
              state.length -= copy;
              do {
                output[put++] = from_source[from++];
              } while (--copy);
              if (state.length === 0) { state.mode = LEN; }
              break;
            case LIT:
              if (left === 0) { break inf_leave; }
              output[put++] = state.length;
              left--;
              state.mode = LEN;
              break;
            case CHECK:
              if (state.wrap) {
                //=== NEEDBITS(32);
                while (bits < 32) {
                  if (have === 0) { break inf_leave; }
                  have--;
                  // Use '|' instead of '+' to make sure that result is signed
                  hold |= input[next++] << bits;
                  bits += 8;
                }
                //===//
                _out -= left;
                strm.total_out += _out;
                state.total += _out;
                if ((state.wrap & 4) && _out) {
                  strm.adler = state.check =
                      /*UPDATE_CHECK(state.check, put - _out, _out);*/
                      (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out));
    
                }
                _out = left;
                // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
                if ((state.wrap & 4) && (state.flags ? hold : zswap32(hold)) !== state.check) {
                  strm.msg = 'incorrect data check';
                  state.mode = BAD;
                  break;
                }
                //=== INITBITS();
                hold = 0;
                bits = 0;
                //===//
                //Tracev((stderr, "inflate:   check matches trailer\n"));
              }
              state.mode = LENGTH;
              /* falls through */
            case LENGTH:
              if (state.wrap && state.flags) {
                //=== NEEDBITS(32);
                while (bits < 32) {
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                //===//
                if ((state.wrap & 4) && hold !== (state.total & 0xffffffff)) {
                  strm.msg = 'incorrect length check';
                  state.mode = BAD;
                  break;
                }
                //=== INITBITS();
                hold = 0;
                bits = 0;
                //===//
                //Tracev((stderr, "inflate:   length matches trailer\n"));
              }
              state.mode = DONE;
              /* falls through */
            case DONE:
              ret = Z_STREAM_END$1;
              break inf_leave;
            case BAD:
              ret = Z_DATA_ERROR$1;
              break inf_leave;
            case MEM:
              return Z_MEM_ERROR$1;
            case SYNC:
              /* falls through */
            default:
              return Z_STREAM_ERROR$1;
          }
        }
    
        // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
    
        /*
           Return from inflate(), updating the total counts and the check value.
           If there was no progress during the inflate() call, return a buffer
           error.  Call updatewindow() to create and/or update the window state.
           Note: a memory error from inflate() is non-recoverable.
         */
    
        //--- RESTORE() ---
        strm.next_out = put;
        strm.avail_out = left;
        strm.next_in = next;
        strm.avail_in = have;
        state.hold = hold;
        state.bits = bits;
        //---
    
        if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
                            (state.mode < CHECK || flush !== Z_FINISH$1))) {
          if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;
        }
        _in -= strm.avail_in;
        _out -= strm.avail_out;
        strm.total_in += _in;
        strm.total_out += _out;
        state.total += _out;
        if ((state.wrap & 4) && _out) {
          strm.adler = state.check = /*UPDATE_CHECK(state.check, strm.next_out - _out, _out);*/
            (state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out));
        }
        strm.data_type = state.bits + (state.last ? 64 : 0) +
                          (state.mode === TYPE ? 128 : 0) +
                          (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
        if (((_in === 0 && _out === 0) || flush === Z_FINISH$1) && ret === Z_OK$1) {
          ret = Z_BUF_ERROR;
        }
        return ret;
      };
    
    
      const inflateEnd = (strm) => {
    
        if (inflateStateCheck(strm)) {
          return Z_STREAM_ERROR$1;
        }
    
        let state = strm.state;
        if (state.window) {
          state.window = null;
        }
        strm.state = null;
        return Z_OK$1;
      };
    
    
      const inflateGetHeader = (strm, head) => {
    
        /* check state */
        if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }
        const state = strm.state;
        if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; }
    
        /* save header structure */
        state.head = head;
        head.done = false;
        return Z_OK$1;
      };
    
    
      const inflateSetDictionary = (strm, dictionary) => {
        const dictLength = dictionary.length;
    
        let state;
        let dictid;
        let ret;
    
        /* check state */
        if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }
        state = strm.state;
    
        if (state.wrap !== 0 && state.mode !== DICT) {
          return Z_STREAM_ERROR$1;
        }
    
        /* check for correct dictionary identifier */
        if (state.mode === DICT) {
          dictid = 1; /* adler32(0, null, 0)*/
          /* dictid = adler32(dictid, dictionary, dictLength); */
          dictid = adler32_1(dictid, dictionary, dictLength, 0);
          if (dictid !== state.check) {
            return Z_DATA_ERROR$1;
          }
        }
        /* copy dictionary to window using updatewindow(), which will amend the
         existing dictionary if appropriate */
        ret = updatewindow(strm, dictionary, dictLength, dictLength);
        if (ret) {
          state.mode = MEM;
          return Z_MEM_ERROR$1;
        }
        state.havedict = 1;
        // Tracev((stderr, "inflate:   dictionary set\n"));
        return Z_OK$1;
      };
    
    
      var inflateReset_1 = inflateReset;
      var inflateReset2_1 = inflateReset2;
      var inflateResetKeep_1 = inflateResetKeep;
      var inflateInit_1 = inflateInit;
      var inflateInit2_1 = inflateInit2;
      var inflate_2$1 = inflate$2;
      var inflateEnd_1 = inflateEnd;
      var inflateGetHeader_1 = inflateGetHeader;
      var inflateSetDictionary_1 = inflateSetDictionary;
      var inflateInfo = 'pako inflate (from Nodeca project)';
    
      /* Not implemented
      module.exports.inflateCodesUsed = inflateCodesUsed;
      module.exports.inflateCopy = inflateCopy;
      module.exports.inflateGetDictionary = inflateGetDictionary;
      module.exports.inflateMark = inflateMark;
      module.exports.inflatePrime = inflatePrime;
      module.exports.inflateSync = inflateSync;
      module.exports.inflateSyncPoint = inflateSyncPoint;
      module.exports.inflateUndermine = inflateUndermine;
      module.exports.inflateValidate = inflateValidate;
      */
    
      var inflate_1$2 = {
          inflateReset: inflateReset_1,
          inflateReset2: inflateReset2_1,
          inflateResetKeep: inflateResetKeep_1,
          inflateInit: inflateInit_1,
          inflateInit2: inflateInit2_1,
          inflate: inflate_2$1,
          inflateEnd: inflateEnd_1,
          inflateGetHeader: inflateGetHeader_1,
          inflateSetDictionary: inflateSetDictionary_1,
          inflateInfo: inflateInfo
      };
    
      // (C) 1995-2013 Jean-loup Gailly and Mark Adler
      // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
      //
      // This software is provided 'as-is', without any express or implied
      // warranty. In no event will the authors be held liable for any damages
      // arising from the use of this software.
      //
      // Permission is granted to anyone to use this software for any purpose,
      // including commercial applications, and to alter it and redistribute it
      // freely, subject to the following restrictions:
      //
      // 1. The origin of this software must not be misrepresented; you must not
      //   claim that you wrote the original software. If you use this software
      //   in a product, an acknowledgment in the product documentation would be
      //   appreciated but is not required.
      // 2. Altered source versions must be plainly marked as such, and must not be
      //   misrepresented as being the original software.
      // 3. This notice may not be removed or altered from any source distribution.
    
      function GZheader() {
        /* true if compressed data believed to be text */
        this.text       = 0;
        /* modification time */
        this.time       = 0;
        /* extra flags (not used when writing a gzip file) */
        this.xflags     = 0;
        /* operating system */
        this.os         = 0;
        /* pointer to extra field or Z_NULL if none */
        this.extra      = null;
        /* extra field length (valid if extra != Z_NULL) */
        this.extra_len  = 0; // Actually, we don't need it in JS,
                             // but leave for few code modifications
    
        //
        // Setup limits is not necessary because in js we should not preallocate memory
        // for inflate use constant limit in 65536 bytes
        //
    
        /* space at extra (only when reading header) */
        // this.extra_max  = 0;
        /* pointer to zero-terminated file name or Z_NULL */
        this.name       = '';
        /* space at name (only when reading header) */
        // this.name_max   = 0;
        /* pointer to zero-terminated comment or Z_NULL */
        this.comment    = '';
        /* space at comment (only when reading header) */
        // this.comm_max   = 0;
        /* true if there was or will be a header crc */
        this.hcrc       = 0;
        /* true when done reading gzip header (not used when writing a gzip file) */
        this.done       = false;
      }
    
      var gzheader = GZheader;
    
      const toString = Object.prototype.toString;
    
      /* Public constants ==========================================================*/
      /* ===========================================================================*/
    
      const {
        Z_NO_FLUSH, Z_FINISH,
        Z_OK, Z_STREAM_END, Z_NEED_DICT, Z_STREAM_ERROR, Z_DATA_ERROR, Z_MEM_ERROR
      } = constants$2;
    
      /* ===========================================================================*/
    
    
      /**
       * class Inflate
       *
       * Generic JS-style wrapper for zlib calls. If you don't need
       * streaming behaviour - use more simple functions: [[inflate]]
       * and [[inflateRaw]].
       **/
    
      /* internal
       * inflate.chunks -> Array
       *
       * Chunks of output data, if [[Inflate#onData]] not overridden.
       **/
    
      /**
       * Inflate.result -> Uint8Array|String
       *
       * Uncompressed result, generated by default [[Inflate#onData]]
       * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
       * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
       **/
    
      /**
       * Inflate.err -> Number
       *
       * Error code after inflate finished. 0 (Z_OK) on success.
       * Should be checked if broken data possible.
       **/
    
      /**
       * Inflate.msg -> String
       *
       * Error message, if [[Inflate.err]] != 0
       **/
    
    
      /**
       * new Inflate(options)
       * - options (Object): zlib inflate options.
       *
       * Creates new inflator instance with specified params. Throws exception
       * on bad params. Supported options:
       *
       * - `windowBits`
       * - `dictionary`
       *
       * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
       * for more information on these.
       *
       * Additional options, for internal needs:
       *
       * - `chunkSize` - size of generated data chunks (16K by default)
       * - `raw` (Boolean) - do raw inflate
       * - `to` (String) - if equal to 'string', then result will be converted
       *   from utf8 to utf16 (javascript) string. When string output requested,
       *   chunk length can differ from `chunkSize`, depending on content.
       *
       * By default, when no options set, autodetect deflate/gzip data format via
       * wrapper header.
       *
       * ##### Example:
       *
       * ```javascript
       * const pako = require('pako')
       * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])
       * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);
       *
       * const inflate = new pako.Inflate({ level: 3});
       *
       * inflate.push(chunk1, false);
       * inflate.push(chunk2, true);  // true -> last chunk
       *
       * if (inflate.err) { throw new Error(inflate.err); }
       *
       * console.log(inflate.result);
       * ```
       **/
      function Inflate$1(options) {
        this.options = common.assign({
          chunkSize: 1024 * 64,
          windowBits: 15,
          to: ''
        }, options || {});
    
        const opt = this.options;
    
        // Force window size for `raw` data, if not set directly,
        // because we have no header for autodetect.
        if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
          opt.windowBits = -opt.windowBits;
          if (opt.windowBits === 0) { opt.windowBits = -15; }
        }
    
        // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
        if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
            !(options && options.windowBits)) {
          opt.windowBits += 32;
        }
    
        // Gzip header has no info about windows size, we can do autodetect only
        // for deflate. So, if window size not set, force it to max when gzip possible
        if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
          // bit 3 (16) -> gzipped data
          // bit 4 (32) -> autodetect gzip/deflate
          if ((opt.windowBits & 15) === 0) {
            opt.windowBits |= 15;
          }
        }
    
        this.err    = 0;      // error code, if happens (0 = Z_OK)
        this.msg    = '';     // error message
        this.ended  = false;  // used to avoid multiple onEnd() calls
        this.chunks = [];     // chunks of compressed data
    
        this.strm   = new zstream();
        this.strm.avail_out = 0;
    
        let status  = inflate_1$2.inflateInit2(
          this.strm,
          opt.windowBits
        );
    
        if (status !== Z_OK) {
          throw new Error(messages[status]);
        }
    
        this.header = new gzheader();
    
        inflate_1$2.inflateGetHeader(this.strm, this.header);
    
        // Setup dictionary
        if (opt.dictionary) {
          // Convert data if needed
          if (typeof opt.dictionary === 'string') {
            opt.dictionary = strings.string2buf(opt.dictionary);
          } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
            opt.dictionary = new Uint8Array(opt.dictionary);
          }
          if (opt.raw) { //In raw mode we need to set the dictionary early
            status = inflate_1$2.inflateSetDictionary(this.strm, opt.dictionary);
            if (status !== Z_OK) {
              throw new Error(messages[status]);
            }
          }
        }
      }
    
      /**
       * Inflate#push(data[, flush_mode]) -> Boolean
       * - data (Uint8Array|ArrayBuffer): input data
       * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE
       *   flush modes. See constants. Skipped or `false` means Z_NO_FLUSH,
       *   `true` means Z_FINISH.
       *
       * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
       * new output chunks. Returns `true` on success. If end of stream detected,
       * [[Inflate#onEnd]] will be called.
       *
       * `flush_mode` is not needed for normal operation, because end of stream
       * detected automatically. You may try to use it for advanced things, but
       * this functionality was not tested.
       *
       * On fail call [[Inflate#onEnd]] with error code and return false.
       *
       * ##### Example
       *
       * ```javascript
       * push(chunk, false); // push one of data chunks
       * ...
       * push(chunk, true);  // push last chunk
       * ```
       **/
      Inflate$1.prototype.push = function (data, flush_mode) {
        const strm = this.strm;
        const chunkSize = this.options.chunkSize;
        const dictionary = this.options.dictionary;
        let status, _flush_mode, last_avail_out;
    
        if (this.ended) return false;
    
        if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;
        else _flush_mode = flush_mode === true ? Z_FINISH : Z_NO_FLUSH;
    
        // Convert data if needed
        if (toString.call(data) === '[object ArrayBuffer]') {
          strm.input = new Uint8Array(data);
        } else {
          strm.input = data;
        }
    
        strm.next_in = 0;
        strm.avail_in = strm.input.length;
    
        for (;;) {
          if (strm.avail_out === 0) {
            strm.output = new Uint8Array(chunkSize);
            strm.next_out = 0;
            strm.avail_out = chunkSize;
          }
    
          status = inflate_1$2.inflate(strm, _flush_mode);
    
          if (status === Z_NEED_DICT && dictionary) {
            status = inflate_1$2.inflateSetDictionary(strm, dictionary);
    
            if (status === Z_OK) {
              status = inflate_1$2.inflate(strm, _flush_mode);
            } else if (status === Z_DATA_ERROR) {
              // Replace code with more verbose
              status = Z_NEED_DICT;
            }
          }
    
          // Skip snyc markers if more data follows and not raw mode
          while (strm.avail_in > 0 &&
                 status === Z_STREAM_END &&
                 strm.state.wrap > 0 &&
                 data[strm.next_in] !== 0)
          {
            inflate_1$2.inflateReset(strm);
            status = inflate_1$2.inflate(strm, _flush_mode);
          }
    
          switch (status) {
            case Z_STREAM_ERROR:
            case Z_DATA_ERROR:
            case Z_NEED_DICT:
            case Z_MEM_ERROR:
              this.onEnd(status);
              this.ended = true;
              return false;
          }
    
          // Remember real `avail_out` value, because we may patch out buffer content
          // to align utf8 strings boundaries.
          last_avail_out = strm.avail_out;
    
          if (strm.next_out) {
            if (strm.avail_out === 0 || status === Z_STREAM_END) {
    
              if (this.options.to === 'string') {
    
                let next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
    
                let tail = strm.next_out - next_out_utf8;
                let utf8str = strings.buf2string(strm.output, next_out_utf8);
    
                // move tail & realign counters
                strm.next_out = tail;
                strm.avail_out = chunkSize - tail;
                if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0);
    
                this.onData(utf8str);
    
              } else {
                this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out));
              }
            }
          }
    
          // Must repeat iteration if out buffer is full
          if (status === Z_OK && last_avail_out === 0) continue;
    
          // Finalize if end of stream reached.
          if (status === Z_STREAM_END) {
            status = inflate_1$2.inflateEnd(this.strm);
            this.onEnd(status);
            this.ended = true;
            return true;
          }
    
          if (strm.avail_in === 0) break;
        }
    
        return true;
      };
    
    
      /**
       * Inflate#onData(chunk) -> Void
       * - chunk (Uint8Array|String): output data. When string output requested,
       *   each chunk will be string.
       *
       * By default, stores data blocks in `chunks[]` property and glue
       * those in `onEnd`. Override this handler, if you need another behaviour.
       **/
      Inflate$1.prototype.onData = function (chunk) {
        this.chunks.push(chunk);
      };
    
    
      /**
       * Inflate#onEnd(status) -> Void
       * - status (Number): inflate status. 0 (Z_OK) on success,
       *   other if not.
       *
       * Called either after you tell inflate that the input stream is
       * complete (Z_FINISH). By default - join collected chunks,
       * free memory and fill `results` / `err` properties.
       **/
      Inflate$1.prototype.onEnd = function (status) {
        // On success - join
        if (status === Z_OK) {
          if (this.options.to === 'string') {
            this.result = this.chunks.join('');
          } else {
            this.result = common.flattenChunks(this.chunks);
          }
        }
        this.chunks = [];
        this.err = status;
        this.msg = this.strm.msg;
      };
    
    
      /**
       * inflate(data[, options]) -> Uint8Array|String
       * - data (Uint8Array|ArrayBuffer): input data to decompress.
       * - options (Object): zlib inflate options.
       *
       * Decompress `data` with inflate/ungzip and `options`. Autodetect
       * format via wrapper header by default. That's why we don't provide
       * separate `ungzip` method.
       *
       * Supported options are:
       *
       * - windowBits
       *
       * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
       * for more information.
       *
       * Sugar (options):
       *
       * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
       *   negative windowBits implicitly.
       * - `to` (String) - if equal to 'string', then result will be converted
       *   from utf8 to utf16 (javascript) string. When string output requested,
       *   chunk length can differ from `chunkSize`, depending on content.
       *
       *
       * ##### Example:
       *
       * ```javascript
       * const pako = require('pako');
       * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9]));
       * let output;
       *
       * try {
       *   output = pako.inflate(input);
       * } catch (err) {
       *   console.log(err);
       * }
       * ```
       **/
      function inflate$1(input, options) {
        const inflator = new Inflate$1(options);
    
        inflator.push(input);
    
        // That will never happens, if you don't cheat with options :)
        if (inflator.err) throw inflator.msg || messages[inflator.err];
    
        return inflator.result;
      }
    
    
      /**
       * inflateRaw(data[, options]) -> Uint8Array|String
       * - data (Uint8Array|ArrayBuffer): input data to decompress.
       * - options (Object): zlib inflate options.
       *
       * The same as [[inflate]], but creates raw data, without wrapper
       * (header and adler32 crc).
       **/
      function inflateRaw$1(input, options) {
        options = options || {};
        options.raw = true;
        return inflate$1(input, options);
      }
    
    
      /**
       * ungzip(data[, options]) -> Uint8Array|String
       * - data (Uint8Array|ArrayBuffer): input data to decompress.
       * - options (Object): zlib inflate options.
       *
       * Just shortcut to [[inflate]], because it autodetects format
       * by header.content. Done for convenience.
       **/
    
    
      var Inflate_1$1 = Inflate$1;
      var inflate_2 = inflate$1;
      var inflateRaw_1$1 = inflateRaw$1;
      var ungzip$1 = inflate$1;
      var constants = constants$2;
    
      var inflate_1$1 = {
          Inflate: Inflate_1$1,
          inflate: inflate_2,
          inflateRaw: inflateRaw_1$1,
          ungzip: ungzip$1,
          constants: constants
      };
    
      const { Deflate, deflate, deflateRaw, gzip } = deflate_1$1;
    
      const { Inflate, inflate, inflateRaw, ungzip } = inflate_1$1;
    
    
    
      var Deflate_1 = Deflate;
      var deflate_1 = deflate;
      var deflateRaw_1 = deflateRaw;
      var gzip_1 = gzip;
      var Inflate_1 = Inflate;
      var inflate_1 = inflate;
      var inflateRaw_1 = inflateRaw;
      var ungzip_1 = ungzip;
      var constants_1 = constants$2;
    
      var pako = {
          Deflate: Deflate_1,
          deflate: deflate_1,
          deflateRaw: deflateRaw_1,
          gzip: gzip_1,
          Inflate: Inflate_1,
          inflate: inflate_1,
          inflateRaw: inflateRaw_1,
          ungzip: ungzip_1,
          constants: constants_1
      };

  var RecordEvents=[];
  var RecordStart=0;
  var Replayurl='';
  var NodeType;
  (function(NodeType2) {
    NodeType2[NodeType2["Document"] = 0] = "Document";
    NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
    NodeType2[NodeType2["Element"] = 2] = "Element";
    NodeType2[NodeType2["Text"] = 3] = "Text";
    NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
    NodeType2[NodeType2["Comment"] = 5] = "Comment";
  })(NodeType || (NodeType = {}));
  function isElement(n) {
    return n.nodeType === n.ELEMENT_NODE;
  }
  function isShadowRoot(n) {
    var host = n === null || n === void 0 ? void 0 : n.host;
    return Boolean((host === null || host === void 0 ? void 0 : host.shadowRoot) === n);
  }
  function isNativeShadowDom(shadowRoot) {
    return Object.prototype.toString.call(shadowRoot) === "[object ShadowRoot]";
  }
  function fixBrowserCompatibilityIssuesInCSS(cssText) {
    if (cssText.includes(" background-clip: text;") && !cssText.includes(" -webkit-background-clip: text;")) {
      cssText = cssText.replace(" background-clip: text;", " -webkit-background-clip: text; background-clip: text;");
    }
    return cssText;
  }
  function getCssRulesString(s) {
    try {
      var rules = s.rules || s.cssRules;
      return rules ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules).map(getCssRuleString).join("")) : null;
    } catch (error) {
      return null;
    }
  }
  function getCssRuleString(rule) {
    var cssStringified = rule.cssText;
    if (isCSSImportRule(rule)) {
      try {
        cssStringified = getCssRulesString(rule.styleSheet) || cssStringified;
      } catch (_a) {
      }
    }
    return cssStringified;
  }
  function isCSSImportRule(rule) {
    return "styleSheet" in rule;
  }
  var Mirror = function() {
    function Mirror2() {
      this.idNodeMap = /* @__PURE__ */ new Map();
      this.nodeMetaMap = /* @__PURE__ */ new WeakMap();
    }
    Mirror2.prototype.getId = function(n) {
      var _a;
      if (!n)
        return -1;
      var id = (_a = this.getMeta(n)) === null || _a === void 0 ? void 0 : _a.id;
      return id !== null && id !== void 0 ? id : -1;
    };
    Mirror2.prototype.getNode = function(id) {
      return this.idNodeMap.get(id) || null;
    };
    Mirror2.prototype.getIds = function() {
      return Array.from(this.idNodeMap.keys());
    };
    Mirror2.prototype.getMeta = function(n) {
      return this.nodeMetaMap.get(n) || null;
    };
    Mirror2.prototype.removeNodeFromMap = function(n) {
      var _this = this;
      var id = this.getId(n);
      this.idNodeMap["delete"](id);
      if (n.childNodes) {
        n.childNodes.forEach(function(childNode) {
          return _this.removeNodeFromMap(childNode);
        });
      }
    };
    Mirror2.prototype.has = function(id) {
      return this.idNodeMap.has(id);
    };
    Mirror2.prototype.hasNode = function(node) {
      return this.nodeMetaMap.has(node);
    };
    Mirror2.prototype.add = function(n, meta) {
      var id = meta.id;
      this.idNodeMap.set(id, n);
      this.nodeMetaMap.set(n, meta);
    };
    Mirror2.prototype.replace = function(id, n) {
      var oldNode = this.getNode(id);
      if (oldNode) {
        var meta = this.nodeMetaMap.get(oldNode);
        if (meta)
          this.nodeMetaMap.set(n, meta);
      }
      this.idNodeMap.set(id, n);
    };
    Mirror2.prototype.reset = function() {
      this.idNodeMap = /* @__PURE__ */ new Map();
      this.nodeMetaMap = /* @__PURE__ */ new WeakMap();
    };
    return Mirror2;
  }();
  function createMirror() {
    return new Mirror();
  }
  function maskInputValue(_a) {
    var element = _a.element, maskInputOptions = _a.maskInputOptions, tagName = _a.tagName, type = _a.type, value = _a.value, maskInputFn = _a.maskInputFn;
    var text = value || "";
    var actualType = type && type.toLowerCase();
    if (maskInputOptions[tagName.toLowerCase()] || actualType && maskInputOptions[actualType]) {
      if (maskInputFn) {
        text = maskInputFn(text, element);
      } else {
        text = "*".repeat(text.length);
      }
    }
    return text;
  }
  var ORIGINAL_ATTRIBUTE_NAME = "__rrweb_original__";
  function is2DCanvasBlank(canvas) {
    var ctx = canvas.getContext("2d");
    if (!ctx)
      return true;
    var chunkSize = 50;
    for (var x = 0; x < canvas.width; x += chunkSize) {
      for (var y = 0; y < canvas.height; y += chunkSize) {
        var getImageData = ctx.getImageData;
        var originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData;
        var pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);
        if (pixelBuffer.some(function(pixel) {
          return pixel !== 0;
        }))
          return false;
      }
    }
    return true;
  }
  function getInputType(element) {
    var type = element.type;
    return element.hasAttribute("data-rr-is-password") ? "password" : type ? type.toLowerCase() : null;
  }
  var _id = 1;
  var tagNameRegex = new RegExp("[^a-z0-9-_:]");
  var IGNORED_NODE = -2;
  function genId() {
    return _id++;
  }
  function getValidTagName(element) {
    if (element instanceof HTMLFormElement) {
      return "form";
    }
    var processedTagName = element.tagName.toLowerCase().trim();
    if (tagNameRegex.test(processedTagName)) {
      return "div";
    }
    return processedTagName;
  }
  function stringifyStyleSheet(sheet) {
    return sheet.cssRules ? Array.from(sheet.cssRules).map(function(rule) {
      return rule.cssText || "";
    }).join("") : "";
  }
  function extractOrigin(url) {
    var origin = "";
    if (url.indexOf("//") > -1) {
      origin = url.split("/").slice(0, 3).join("/");
    } else {
      origin = url.split("/")[0];
    }
    origin = origin.split("?")[0];
    return origin;
  }
  var canvasService;
  var canvasCtx;
  var URL_IN_CSS_REF = /url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm;
  var URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\/\//i;
  var URL_WWW_MATCH = /^www\..*/i;
  var DATA_URI = /^(data:)([^,]*),(.*)/i;
  function absoluteToStylesheet(cssText, href) {
    return (cssText || "").replace(URL_IN_CSS_REF, function(origin, quote1, path1, quote2, path2, path3) {
      var filePath = path1 || path2 || path3;
      var maybeQuote = quote1 || quote2 || "";
      if (!filePath) {
        return origin;
      }
      if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {
        return "url(".concat(maybeQuote).concat(filePath).concat(maybeQuote, ")");
      }
      if (DATA_URI.test(filePath)) {
        return "url(".concat(maybeQuote).concat(filePath).concat(maybeQuote, ")");
      }
      if (filePath[0] === "/") {
        return "url(".concat(maybeQuote).concat(extractOrigin(href) + filePath).concat(maybeQuote, ")");
      }
      var stack = href.split("/");
      var parts = filePath.split("/");
      stack.pop();
      for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
        var part = parts_1[_i];
        if (part === ".") {
          continue;
        } else if (part === "..") {
          stack.pop();
        } else {
          stack.push(part);
        }
      }
      return "url(".concat(maybeQuote).concat(stack.join("/")).concat(maybeQuote, ")");
    });
  }
  var SRCSET_NOT_SPACES = /^[^ \t\n\r\u000c]+/;
  var SRCSET_COMMAS_OR_SPACES = /^[, \t\n\r\u000c]+/;
  function getAbsoluteSrcsetString(doc, attributeValue) {
    if (attributeValue.trim() === "") {
      return attributeValue;
    }
    var pos = 0;
    function collectCharacters(regEx) {
      var chars;
      var match = regEx.exec(attributeValue.substring(pos));
      if (match) {
        chars = match[0];
        pos += chars.length;
        return chars;
      }
      return "";
    }
    var output = [];
    while (true) {
      collectCharacters(SRCSET_COMMAS_OR_SPACES);
      if (pos >= attributeValue.length) {
        break;
      }
      var url = collectCharacters(SRCSET_NOT_SPACES);
      if (url.slice(-1) === ",") {
        url = absoluteToDoc(doc, url.substring(0, url.length - 1));
        output.push(url);
      } else {
        var descriptorsStr = "";
        url = absoluteToDoc(doc, url);
        var inParens = false;
        while (true) {
          var c = attributeValue.charAt(pos);
          if (c === "") {
            output.push((url + descriptorsStr).trim());
            break;
          } else if (!inParens) {
            if (c === ",") {
              pos += 1;
              output.push((url + descriptorsStr).trim());
              break;
            } else if (c === "(") {
              inParens = true;
            }
          } else {
            if (c === ")") {
              inParens = false;
            }
          }
          descriptorsStr += c;
          pos += 1;
        }
      }
    }
    return output.join(", ");
  }
  function absoluteToDoc(doc, attributeValue) {
    if (!attributeValue || attributeValue.trim() === "") {
      return attributeValue;
    }
    var a = doc.createElement("a");
    a.href = attributeValue;
    return a.href;
  }
  function isSVGElement(el) {
    return Boolean(el.tagName === "svg" || el.ownerSVGElement);
  }
  function getHref() {
    var a = document.createElement("a");
    a.href = "";
    return a.href;
  }
  function transformAttribute(doc, tagName, name, value) {
    if (!value) {
      return value;
    }
    if (name === "src" || name === "href" && !(tagName === "use" && value[0] === "#")) {
      return absoluteToDoc(doc, value);
    } else if (name === "xlink:href" && value[0] !== "#") {
      return absoluteToDoc(doc, value);
    } else if (name === "background" && (tagName === "table" || tagName === "td" || tagName === "th")) {
      return absoluteToDoc(doc, value);
    } else if (name === "srcset") {
      return getAbsoluteSrcsetString(doc, value);
    } else if (name === "style") {
      return absoluteToStylesheet(value, getHref());
    } else if (tagName === "object" && name === "data") {
      return absoluteToDoc(doc, value);
    }
    return value;
  }
  function ignoreAttribute(tagName, name, _value) {
    return (tagName === "video" || tagName === "audio") && name === "autoplay";
  }
  function _isBlockedElement(element, blockClass, blockSelector) {
    try {
      if (typeof blockClass === "string") {
        if (element.classList.contains(blockClass)) {
          return true;
        }
      } else {
        for (var eIndex = element.classList.length; eIndex--; ) {
          var className = element.classList[eIndex];
          if (blockClass.test(className)) {
            return true;
          }
        }
      }
      if (blockSelector) {
        return element.matches(blockSelector);
      }
    } catch (e) {
    }
    return false;
  }
  function classMatchesRegex(node, regex, checkAncestors) {
    if (!node)
      return false;
    if (node.nodeType !== node.ELEMENT_NODE) {
      if (!checkAncestors)
        return false;
      return classMatchesRegex(node.parentNode, regex, checkAncestors);
    }
    for (var eIndex = node.classList.length; eIndex--; ) {
      var className = node.classList[eIndex];
      if (regex.test(className)) {
        return true;
      }
    }
    if (!checkAncestors)
      return false;
    return classMatchesRegex(node.parentNode, regex, checkAncestors);
  }
  function needMaskingText(node, maskTextClass, maskTextSelector) {
    try {
      var el = node.nodeType === node.ELEMENT_NODE ? node : node.parentElement;
      if (el === null)
        return false;
      if (typeof maskTextClass === "string") {
        if (el.classList.contains(maskTextClass))
          return true;
        if (el.closest(".".concat(maskTextClass)))
          return true;
      } else {
        if (classMatchesRegex(el, maskTextClass, true))
          return true;
      }
      if (maskTextSelector) {
        if (el.matches(maskTextSelector))
          return true;
        if (el.closest(maskTextSelector))
          return true;
      }
    } catch (e) {
    }
    return false;
  }
  function onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {
    var win = iframeEl.contentWindow;
    if (!win) {
      return;
    }
    var fired = false;
    var readyState;
    try {
      readyState = win.document.readyState;
    } catch (error) {
      return;
    }
    if (readyState !== "complete") {
      var timer_1 = setTimeout(function() {
        if (!fired) {
          listener();
          fired = true;
        }
      }, iframeLoadTimeout);
      iframeEl.addEventListener("load", function() {
        clearTimeout(timer_1);
        fired = true;
        listener();
      });
      return;
    }
    var blankUrl = "about:blank";
    if (win.location.href !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === "") {
      setTimeout(listener, 0);
      return iframeEl.addEventListener("load", listener);
    }
    iframeEl.addEventListener("load", listener);
  }
  function onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {
    var fired = false;
    var styleSheetLoaded;
    try {
      styleSheetLoaded = link.sheet;
    } catch (error) {
      return;
    }
    if (styleSheetLoaded)
      return;
    var timer = setTimeout(function() {
      if (!fired) {
        listener();
        fired = true;
      }
    }, styleSheetLoadTimeout);
    link.addEventListener("load", function() {
      clearTimeout(timer);
      fired = true;
      listener();
    });
  }
  function serializeNode(n, options) {
    var doc = options.doc, mirror = options.mirror, blockClass = options.blockClass, blockSelector = options.blockSelector, maskTextClass = options.maskTextClass, maskTextSelector = options.maskTextSelector, inlineStylesheet = options.inlineStylesheet, _a = options.maskInputOptions, maskInputOptions = _a === void 0 ? {} : _a, maskTextFn = options.maskTextFn, maskInputFn = options.maskInputFn, _b = options.dataURLOptions, dataURLOptions = _b === void 0 ? {} : _b, inlineImages = options.inlineImages, recordCanvas = options.recordCanvas, keepIframeSrcFn = options.keepIframeSrcFn, _c = options.newlyAddedElement, newlyAddedElement = _c === void 0 ? false : _c;
    var rootId = getRootId(doc, mirror);
    switch (n.nodeType) {
      case n.DOCUMENT_NODE:
        if (n.compatMode !== "CSS1Compat") {
          return {
            type: NodeType.Document,
            childNodes: [],
            compatMode: n.compatMode
          };
        } else {
          return {
            type: NodeType.Document,
            childNodes: []
          };
        }
      case n.DOCUMENT_TYPE_NODE:
        return {
          type: NodeType.DocumentType,
          name: n.name,
          publicId: n.publicId,
          systemId: n.systemId,
          rootId
        };
      case n.ELEMENT_NODE:
        return serializeElementNode(n, {
          doc,
          blockClass,
          blockSelector,
          inlineStylesheet,
          maskInputOptions,
          maskInputFn,
          dataURLOptions,
          inlineImages,
          recordCanvas,
          keepIframeSrcFn,
          newlyAddedElement,
          rootId
        });
      case n.TEXT_NODE:
        return serializeTextNode(n, {
          maskTextClass,
          maskTextSelector,
          maskTextFn,
          rootId
        });
      case n.CDATA_SECTION_NODE:
        return {
          type: NodeType.CDATA,
          textContent: "",
          rootId
        };
      case n.COMMENT_NODE:
        return {
          type: NodeType.Comment,
          textContent: n.textContent || "",
          rootId
        };
      default:
        return false;
    }
  }
  function getRootId(doc, mirror) {
    if (!mirror.hasNode(doc))
      return void 0;
    var docId = mirror.getId(doc);
    return docId === 1 ? void 0 : docId;
  }
  function serializeTextNode(n, options) {
    var _a;
    var maskTextClass = options.maskTextClass, maskTextSelector = options.maskTextSelector, maskTextFn = options.maskTextFn, rootId = options.rootId;
    var parentTagName = n.parentNode && n.parentNode.tagName;
    var textContent = n.textContent;
    var isStyle = parentTagName === "STYLE" ? true : void 0;
    var isScript = parentTagName === "SCRIPT" ? true : void 0;
    if (isStyle && textContent) {
      try {
        if (n.nextSibling || n.previousSibling) {
        } else if ((_a = n.parentNode.sheet) === null || _a === void 0 ? void 0 : _a.cssRules) {
          textContent = stringifyStyleSheet(n.parentNode.sheet);
        }
      } catch (err) {
        console.warn("Cannot get CSS styles from text's parentNode. Error: ".concat(err), n);
      }
      textContent = absoluteToStylesheet(textContent, getHref());
    }
    if (isScript) {
      textContent = "SCRIPT_PLACEHOLDER";
    }
    if (!isStyle && !isScript && textContent && needMaskingText(n, maskTextClass, maskTextSelector)) {
      textContent = maskTextFn ? maskTextFn(textContent) : textContent.replace(/[\S]/g, "*");
    }
    return {
      type: NodeType.Text,
      textContent: textContent || "",
      isStyle,
      rootId
    };
  }
  function serializeElementNode(n, options) {
    var doc = options.doc, blockClass = options.blockClass, blockSelector = options.blockSelector, inlineStylesheet = options.inlineStylesheet, _a = options.maskInputOptions, maskInputOptions = _a === void 0 ? {} : _a, maskInputFn = options.maskInputFn, _b = options.dataURLOptions, dataURLOptions = _b === void 0 ? {} : _b, inlineImages = options.inlineImages, recordCanvas = options.recordCanvas, keepIframeSrcFn = options.keepIframeSrcFn, _c = options.newlyAddedElement, newlyAddedElement = _c === void 0 ? false : _c, rootId = options.rootId;
    var needBlock = _isBlockedElement(n, blockClass, blockSelector);
    var tagName = getValidTagName(n);
    var attributes = {};
    var len = n.attributes.length;
    for (var i = 0; i < len; i++) {
      var attr = n.attributes[i];
      if (!ignoreAttribute(tagName, attr.name, attr.value)) {
        attributes[attr.name] = transformAttribute(doc, tagName, attr.name, attr.value);
      }
    }
    if (tagName === "link" && inlineStylesheet) {
      var stylesheet = Array.from(doc.styleSheets).find(function(s) {
        return s.href === n.href;
      });
      var cssText = null;
      if (stylesheet) {
        cssText = getCssRulesString(stylesheet);
      }
      if (cssText) {
        delete attributes.rel;
        delete attributes.href;
        attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);
      }
    }
    if (tagName === "style" && n.sheet && !(n.innerText || n.textContent || "").trim().length) {
      var cssText = getCssRulesString(n.sheet);
      if (cssText) {
        attributes._cssText = absoluteToStylesheet(cssText, getHref());
      }
    }
    if (tagName === "input" || tagName === "textarea" || tagName === "select") {
      var value = n.value;
      var checked = n.checked;
      if (attributes.type !== "radio" && attributes.type !== "checkbox" && attributes.type !== "submit" && attributes.type !== "button" && value) {
        var type = getInputType(n);
        attributes.value = maskInputValue({
          element: n,
          type,
          tagName,
          value,
          maskInputOptions,
          maskInputFn
        });
      } else if (checked) {
        attributes.checked = checked;
      }
    }
    if (tagName === "option") {
      if (n.selected && !maskInputOptions["select"]) {
        attributes.selected = true;
      } else {
        delete attributes.selected;
      }
    }
    if (tagName === "canvas" && recordCanvas) {
      if (n.__context === "2d") {
        if (!is2DCanvasBlank(n)) {
          attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);
        }
      } else if (!("__context" in n)) {
        var canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);
        var blankCanvas = document.createElement("canvas");
        blankCanvas.width = n.width;
        blankCanvas.height = n.height;
        var blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);
        if (canvasDataURL !== blankCanvasDataURL) {
          attributes.rr_dataURL = canvasDataURL;
        }
      }
    }
    if (tagName === "img" && inlineImages) {
      if (!canvasService) {
        canvasService = doc.createElement("canvas");
        canvasCtx = canvasService.getContext("2d");
      }
      var image_1 = n;
      var oldValue_1 = image_1.crossOrigin;
      image_1.crossOrigin = "anonymous";
      var recordInlineImage_1 = function() {
        image_1.removeEventListener("load", recordInlineImage_1);
        try {
          canvasService.width = image_1.naturalWidth;
          canvasService.height = image_1.naturalHeight;
          canvasCtx.drawImage(image_1, 0, 0);
          attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);
        } catch (err) {
          console.warn("Cannot inline img src=".concat(image_1.currentSrc, "! Error: ").concat(err));
        }
        oldValue_1 ? attributes.crossOrigin = oldValue_1 : image_1.removeAttribute("crossorigin");
      };
      if (image_1.complete && image_1.naturalWidth !== 0)
        recordInlineImage_1();
      else
        image_1.addEventListener("load", recordInlineImage_1);
    }
    if (tagName === "audio" || tagName === "video") {
      attributes.rr_mediaState = n.paused ? "paused" : "played";
      attributes.rr_mediaCurrentTime = n.currentTime;
    }
    if (!newlyAddedElement) {
      if (n.scrollLeft) {
        attributes.rr_scrollLeft = n.scrollLeft;
      }
      if (n.scrollTop) {
        attributes.rr_scrollTop = n.scrollTop;
      }
    }
    if (needBlock) {
      var _d = n.getBoundingClientRect(), width = _d.width, height = _d.height;
      attributes = {
        "class": attributes["class"],
        rr_width: "".concat(width, "px"),
        rr_height: "".concat(height, "px")
      };
    }
    if (tagName === "iframe" && !keepIframeSrcFn(attributes.src)) {
      if (!n.contentDocument) {
        attributes.rr_src = attributes.src;
      }
      delete attributes.src;
    }
    return {
      type: NodeType.Element,
      tagName,
      attributes,
      childNodes: [],
      isSVG: isSVGElement(n) || void 0,
      needBlock,
      rootId
    };
  }
  function lowerIfExists(maybeAttr) {
    if (maybeAttr === void 0 || maybeAttr === null) {
      return "";
    } else {
      return maybeAttr.toLowerCase();
    }
  }
  function slimDOMExcluded(sn, slimDOMOptions) {
    if (slimDOMOptions.comment && sn.type === NodeType.Comment) {
      return true;
    } else if (sn.type === NodeType.Element) {
      if (slimDOMOptions.script && (sn.tagName === "script" || sn.tagName === "link" && (sn.attributes.rel === "preload" || sn.attributes.rel === "modulepreload") && sn.attributes.as === "script" || sn.tagName === "link" && sn.attributes.rel === "prefetch" && typeof sn.attributes.href === "string" && sn.attributes.href.endsWith(".js"))) {
        return true;
      } else if (slimDOMOptions.headFavicon && (sn.tagName === "link" && sn.attributes.rel === "shortcut icon" || sn.tagName === "meta" && (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) || lowerIfExists(sn.attributes.name) === "application-name" || lowerIfExists(sn.attributes.rel) === "icon" || lowerIfExists(sn.attributes.rel) === "apple-touch-icon" || lowerIfExists(sn.attributes.rel) === "shortcut icon"))) {
        return true;
      } else if (sn.tagName === "meta") {
        if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {
          return true;
        } else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === "pinterest")) {
          return true;
        } else if (slimDOMOptions.headMetaRobots && (lowerIfExists(sn.attributes.name) === "robots" || lowerIfExists(sn.attributes.name) === "googlebot" || lowerIfExists(sn.attributes.name) === "bingbot")) {
          return true;
        } else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes["http-equiv"] !== void 0) {
          return true;
        } else if (slimDOMOptions.headMetaAuthorship && (lowerIfExists(sn.attributes.name) === "author" || lowerIfExists(sn.attributes.name) === "generator" || lowerIfExists(sn.attributes.name) === "framework" || lowerIfExists(sn.attributes.name) === "publisher" || lowerIfExists(sn.attributes.name) === "progid" || lowerIfExists(sn.attributes.property).match(/^article:/) || lowerIfExists(sn.attributes.property).match(/^product:/))) {
          return true;
        } else if (slimDOMOptions.headMetaVerification && (lowerIfExists(sn.attributes.name) === "google-site-verification" || lowerIfExists(sn.attributes.name) === "yandex-verification" || lowerIfExists(sn.attributes.name) === "csrf-token" || lowerIfExists(sn.attributes.name) === "p:domain_verify" || lowerIfExists(sn.attributes.name) === "verify-v1" || lowerIfExists(sn.attributes.name) === "verification" || lowerIfExists(sn.attributes.name) === "shopify-checkout-api-token")) {
          return true;
        }
      }
    }
    return false;
  }
  function serializeNodeWithId(n, options) {
    var doc = options.doc, mirror = options.mirror, blockClass = options.blockClass, blockSelector = options.blockSelector, maskTextClass = options.maskTextClass, maskTextSelector = options.maskTextSelector, _a = options.skipChild, skipChild = _a === void 0 ? false : _a, _b = options.inlineStylesheet, inlineStylesheet = _b === void 0 ? true : _b, _c = options.maskInputOptions, maskInputOptions = _c === void 0 ? {} : _c, maskTextFn = options.maskTextFn, maskInputFn = options.maskInputFn, slimDOMOptions = options.slimDOMOptions, _d = options.dataURLOptions, dataURLOptions = _d === void 0 ? {} : _d, _e = options.inlineImages, inlineImages = _e === void 0 ? false : _e, _f = options.recordCanvas, recordCanvas = _f === void 0 ? false : _f, onSerialize = options.onSerialize, onIframeLoad = options.onIframeLoad, _g = options.iframeLoadTimeout, iframeLoadTimeout = _g === void 0 ? 5e3 : _g, onStylesheetLoad = options.onStylesheetLoad, _h = options.stylesheetLoadTimeout, stylesheetLoadTimeout = _h === void 0 ? 5e3 : _h, _j = options.keepIframeSrcFn, keepIframeSrcFn = _j === void 0 ? function() {
      return false;
    } : _j, _k = options.newlyAddedElement, newlyAddedElement = _k === void 0 ? false : _k;
    var _l = options.preserveWhiteSpace, preserveWhiteSpace = _l === void 0 ? true : _l;
    var _serializedNode = serializeNode(n, {
      doc,
      mirror,
      blockClass,
      blockSelector,
      maskTextClass,
      maskTextSelector,
      inlineStylesheet,
      maskInputOptions,
      maskTextFn,
      maskInputFn,
      dataURLOptions,
      inlineImages,
      recordCanvas,
      keepIframeSrcFn,
      newlyAddedElement
    });
    if (!_serializedNode) {
      console.warn(n, "not serialized");
      return null;
    }
    var id;
    if (mirror.hasNode(n)) {
      id = mirror.getId(n);
    } else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType.Text && !_serializedNode.isStyle && !_serializedNode.textContent.replace(/^\s+|\s+$/gm, "").length) {
      id = IGNORED_NODE;
    } else {
      id = genId();
    }
    var serializedNode = Object.assign(_serializedNode, { id });
    mirror.add(n, serializedNode);
    if (id === IGNORED_NODE) {
      return null;
    }
    if (onSerialize) {
      onSerialize(n);
    }
    var recordChild = !skipChild;
    if (serializedNode.type === NodeType.Element) {
      recordChild = recordChild && !serializedNode.needBlock;
      delete serializedNode.needBlock;
      var shadowRoot = n.shadowRoot;
      if (shadowRoot && isNativeShadowDom(shadowRoot))
        serializedNode.isShadowHost = true;
    }
    if ((serializedNode.type === NodeType.Document || serializedNode.type === NodeType.Element) && recordChild) {
      if (slimDOMOptions.headWhitespace && serializedNode.type === NodeType.Element && serializedNode.tagName === "head") {
        preserveWhiteSpace = false;
      }
      var bypassOptions = {
        doc,
        mirror,
        blockClass,
        blockSelector,
        maskTextClass,
        maskTextSelector,
        skipChild,
        inlineStylesheet,
        maskInputOptions,
        maskTextFn,
        maskInputFn,
        slimDOMOptions,
        dataURLOptions,
        inlineImages,
        recordCanvas,
        preserveWhiteSpace,
        onSerialize,
        onIframeLoad,
        iframeLoadTimeout,
        onStylesheetLoad,
        stylesheetLoadTimeout,
        keepIframeSrcFn
      };
      for (var _i = 0, _m = Array.from(n.childNodes); _i < _m.length; _i++) {
        var childN = _m[_i];
        var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
        if (serializedChildNode) {
          serializedNode.childNodes.push(serializedChildNode);
        }
      }
      if (isElement(n) && n.shadowRoot) {
        for (var _o = 0, _p = Array.from(n.shadowRoot.childNodes); _o < _p.length; _o++) {
          var childN = _p[_o];
          var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
          if (serializedChildNode) {
            isNativeShadowDom(n.shadowRoot) && (serializedChildNode.isShadow = true);
            serializedNode.childNodes.push(serializedChildNode);
          }
        }
      }
    }
    if (n.parentNode && isShadowRoot(n.parentNode) && isNativeShadowDom(n.parentNode)) {
      serializedNode.isShadow = true;
    }
    if (serializedNode.type === NodeType.Element && serializedNode.tagName === "iframe") {
      onceIframeLoaded(n, function() {
        var iframeDoc = n.contentDocument;
        if (iframeDoc && onIframeLoad) {
          var serializedIframeNode = serializeNodeWithId(iframeDoc, {
            doc: iframeDoc,
            mirror,
            blockClass,
            blockSelector,
            maskTextClass,
            maskTextSelector,
            skipChild: false,
            inlineStylesheet,
            maskInputOptions,
            maskTextFn,
            maskInputFn,
            slimDOMOptions,
            dataURLOptions,
            inlineImages,
            recordCanvas,
            preserveWhiteSpace,
            onSerialize,
            onIframeLoad,
            iframeLoadTimeout,
            onStylesheetLoad,
            stylesheetLoadTimeout,
            keepIframeSrcFn
          });
          if (serializedIframeNode) {
            onIframeLoad(n, serializedIframeNode);
          }
        }
      }, iframeLoadTimeout);
    }
    if (serializedNode.type === NodeType.Element && serializedNode.tagName === "link" && serializedNode.attributes.rel === "stylesheet") {
      onceStylesheetLoaded(n, function() {
        if (onStylesheetLoad) {
          var serializedLinkNode = serializeNodeWithId(n, {
            doc,
            mirror,
            blockClass,
            blockSelector,
            maskTextClass,
            maskTextSelector,
            skipChild: false,
            inlineStylesheet,
            maskInputOptions,
            maskTextFn,
            maskInputFn,
            slimDOMOptions,
            dataURLOptions,
            inlineImages,
            recordCanvas,
            preserveWhiteSpace,
            onSerialize,
            onIframeLoad,
            iframeLoadTimeout,
            onStylesheetLoad,
            stylesheetLoadTimeout,
            keepIframeSrcFn
          });
          if (serializedLinkNode) {
            onStylesheetLoad(n, serializedLinkNode);
          }
        }
      }, stylesheetLoadTimeout);
    }
    return serializedNode;
  }
  function snapshot(n, options) {
    var _a = options || {}, _b = _a.mirror, mirror = _b === void 0 ? new Mirror() : _b, _c = _a.blockClass, blockClass = _c === void 0 ? "rr-block" : _c, _d = _a.blockSelector, blockSelector = _d === void 0 ? null : _d, _e = _a.maskTextClass, maskTextClass = _e === void 0 ? "rr-mask" : _e, _f = _a.maskTextSelector, maskTextSelector = _f === void 0 ? null : _f, _g = _a.inlineStylesheet, inlineStylesheet = _g === void 0 ? true : _g, _h = _a.inlineImages, inlineImages = _h === void 0 ? false : _h, _j = _a.recordCanvas, recordCanvas = _j === void 0 ? false : _j, _k = _a.maskAllInputs, maskAllInputs = _k === void 0 ? false : _k, maskTextFn = _a.maskTextFn, maskInputFn = _a.maskInputFn, _l = _a.slimDOM, slimDOM = _l === void 0 ? false : _l, dataURLOptions = _a.dataURLOptions, preserveWhiteSpace = _a.preserveWhiteSpace, onSerialize = _a.onSerialize, onIframeLoad = _a.onIframeLoad, iframeLoadTimeout = _a.iframeLoadTimeout, onStylesheetLoad = _a.onStylesheetLoad, stylesheetLoadTimeout = _a.stylesheetLoadTimeout, _m = _a.keepIframeSrcFn, keepIframeSrcFn = _m === void 0 ? function() {
      return false;
    } : _m;
    var maskInputOptions = maskAllInputs === true ? {
      color: true,
      date: true,
      "datetime-local": true,
      email: true,
      month: true,
      number: true,
      range: true,
      search: true,
      tel: true,
      text: true,
      time: true,
      url: true,
      week: true,
      textarea: true,
      select: true,
      password: true
    } : maskAllInputs === false ? {
      password: true
    } : maskAllInputs;
    var slimDOMOptions = slimDOM === true || slimDOM === "all" ? {
      script: true,
      comment: true,
      headFavicon: true,
      headWhitespace: true,
      headMetaDescKeywords: slimDOM === "all",
      headMetaSocial: true,
      headMetaRobots: true,
      headMetaHttpEquiv: true,
      headMetaAuthorship: true,
      headMetaVerification: true
    } : slimDOM === false ? {} : slimDOM;
    return serializeNodeWithId(n, {
      doc: n,
      mirror,
      blockClass,
      blockSelector,
      maskTextClass,
      maskTextSelector,
      skipChild: false,
      inlineStylesheet,
      maskInputOptions,
      maskTextFn,
      maskInputFn,
      slimDOMOptions,
      dataURLOptions,
      inlineImages,
      recordCanvas,
      preserveWhiteSpace,
      onSerialize,
      onIframeLoad,
      iframeLoadTimeout,
      onStylesheetLoad,
      stylesheetLoadTimeout,
      keepIframeSrcFn,
      newlyAddedElement: false
    });
  }

  function on(type, fn, target = document) {
    const options = { capture: true, passive: true };
    target.addEventListener(type, fn, options);
    return () => target.removeEventListener(type, fn, options);
  }
  const DEPARTED_MIRROR_ACCESS_WARNING = "Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.";
  let _mirror = {
    map: {},
    getId() {
      console.error(DEPARTED_MIRROR_ACCESS_WARNING);
      return -1;
    },
    getNode() {
      console.error(DEPARTED_MIRROR_ACCESS_WARNING);
      return null;
    },
    removeNodeFromMap() {
      console.error(DEPARTED_MIRROR_ACCESS_WARNING);
    },
    has() {
      console.error(DEPARTED_MIRROR_ACCESS_WARNING);
      return false;
    },
    reset() {
      console.error(DEPARTED_MIRROR_ACCESS_WARNING);
    }
  };
  if (typeof window !== "undefined" && window.Proxy && window.Reflect) {
    _mirror = new Proxy(_mirror, {
      get(target, prop, receiver) {
        if (prop === "map") {
          console.error(DEPARTED_MIRROR_ACCESS_WARNING);
        }
        return Reflect.get(target, prop, receiver);
      }
    });
  }
  function throttle(func, wait, options = {}) {
    let timeout = null;
    let previous = 0;
    return function(...args) {
      const now = Date.now();
      if (!previous && options.leading === false) {
        previous = now;
      }
      const remaining = wait - (now - previous);
      const context = this;
      if (remaining <= 0 || remaining > wait) {
        if (timeout) {
          clearTimeout(timeout);
          timeout = null;
        }
        previous = now;
        func.apply(context, args);
      } else if (!timeout && options.trailing !== false) {
        timeout = setTimeout(() => {
          previous = options.leading === false ? 0 : Date.now();
          timeout = null;
          func.apply(context, args);
        }, remaining);
      }
    };
  }
  function hookSetter(target, key, d, isRevoked, win = window) {
    const original = win.Object.getOwnPropertyDescriptor(target, key);
    win.Object.defineProperty(target, key, isRevoked ? d : {
      set(value) {
        setTimeout(() => {
          d.set.call(this, value);
        }, 0);
        if (original && original.set) {
          original.set.call(this, value);
        }
      }
    });
    return () => hookSetter(target, key, original || {}, true);
  }
  function patch(source, name, replacement) {
    try {
      if (!(name in source)) {
        return () => {
        };
      }
      const original = source[name];
      const wrapped = replacement(original);
      if (typeof wrapped === "function") {
        wrapped.prototype = wrapped.prototype || {};
        Object.defineProperties(wrapped, {
          __rrweb_original__: {
            enumerable: false,
            value: original
          }
        });
      }
      source[name] = wrapped;
      return () => {
        source[name] = original;
      };
    } catch (e) {
      return () => {
      };
    }
  }
  function getWindowScroll(win) {
    var _a, _b, _c, _d, _e, _f;
    const doc = win.document;
    return {
      left: doc.scrollingElement ? doc.scrollingElement.scrollLeft : win.pageXOffset !== void 0 ? win.pageXOffset : (doc == null ? void 0 : doc.documentElement.scrollLeft) || ((_b = (_a = doc == null ? void 0 : doc.body) == null ? void 0 : _a.parentElement) == null ? void 0 : _b.scrollLeft) || ((_c = doc == null ? void 0 : doc.body) == null ? void 0 : _c.scrollLeft) || 0,
      top: doc.scrollingElement ? doc.scrollingElement.scrollTop : win.pageYOffset !== void 0 ? win.pageYOffset : (doc == null ? void 0 : doc.documentElement.scrollTop) || ((_e = (_d = doc == null ? void 0 : doc.body) == null ? void 0 : _d.parentElement) == null ? void 0 : _e.scrollTop) || ((_f = doc == null ? void 0 : doc.body) == null ? void 0 : _f.scrollTop) || 0
    };
  }
  function getWindowHeight() {
    return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight;
  }
  function getWindowWidth() {
    return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth;
  }
  function isBlocked(node, blockClass, blockSelector, checkAncestors) {
    if (!node) {
      return false;
    }
    const el = node.nodeType === node.ELEMENT_NODE ? node : node.parentElement;
    if (!el)
      return false;
    try {
      if (typeof blockClass === "string") {
        if (el.classList.contains(blockClass))
          return true;
        if (checkAncestors && el.closest("." + blockClass) !== null)
          return true;
      } else {
        if (classMatchesRegex(el, blockClass, checkAncestors))
          return true;
      }
    } catch (e) {
    }
    if (blockSelector) {
      if (el.matches(blockSelector))
        return true;
      if (checkAncestors && el.closest(blockSelector) !== null)
        return true;
    }
    return false;
  }
  function isSerialized(n, mirror) {
    return mirror.getId(n) !== -1;
  }
  function isIgnored(n, mirror) {
    return mirror.getId(n) === IGNORED_NODE;
  }
  function isAncestorRemoved(target, mirror) {
    if (isShadowRoot(target)) {
      return false;
    }
    const id = mirror.getId(target);
    if (!mirror.has(id)) {
      return true;
    }
    if (target.parentNode && target.parentNode.nodeType === target.DOCUMENT_NODE) {
      return false;
    }
    if (!target.parentNode) {
      return true;
    }
    return isAncestorRemoved(target.parentNode, mirror);
  }
  function legacy_isTouchEvent(event) {
    return Boolean(event.changedTouches);
  }
  function polyfill(win = window) {
    if ("NodeList" in win && !win.NodeList.prototype.forEach) {
      win.NodeList.prototype.forEach = Array.prototype.forEach;
    }
    if ("DOMTokenList" in win && !win.DOMTokenList.prototype.forEach) {
      win.DOMTokenList.prototype.forEach = Array.prototype.forEach;
    }
    if (!Node.prototype.contains) {
      Node.prototype.contains = (...args) => {
        let node = args[0];
        if (!(0 in args)) {
          throw new TypeError("1 argument is required");
        }
        do {
          if (this === node) {
            return true;
          }
        } while (node = node && node.parentNode);
        return false;
      };
    }
  }
  function isSerializedIframe(n, mirror) {
    return Boolean(n.nodeName === "IFRAME" && mirror.getMeta(n));
  }
  function isSerializedStylesheet(n, mirror) {
    return Boolean(n.nodeName === "LINK" && n.nodeType === n.ELEMENT_NODE && n.getAttribute && n.getAttribute("rel") === "stylesheet" && mirror.getMeta(n));
  }
  function hasShadowRoot(n) {
    return Boolean(n == null ? void 0 : n.shadowRoot);
  }
  class StyleSheetMirror {
    constructor() {
      this.id = 1;
      this.styleIDMap = /* @__PURE__ */ new WeakMap();
      this.idStyleMap = /* @__PURE__ */ new Map();
    }
    getId(stylesheet) {
      var _a;
      return (_a = this.styleIDMap.get(stylesheet)) != null ? _a : -1;
    }
    has(stylesheet) {
      return this.styleIDMap.has(stylesheet);
    }
    add(stylesheet, id) {
      if (this.has(stylesheet))
        return this.getId(stylesheet);
      let newId;
      if (id === void 0) {
        newId = this.id++;
      } else
        newId = id;
      this.styleIDMap.set(stylesheet, newId);
      this.idStyleMap.set(newId, stylesheet);
      return newId;
    }
    getStyle(id) {
      return this.idStyleMap.get(id) || null;
    }
    reset() {
      this.styleIDMap = /* @__PURE__ */ new WeakMap();
      this.idStyleMap = /* @__PURE__ */ new Map();
      this.id = 1;
    }
    generateId() {
      return this.id++;
    }
  }
  function getShadowHost(n) {
    var _a, _b;
    let shadowHost = null;
    if (((_b = (_a = n.getRootNode) == null ? void 0 : _a.call(n)) == null ? void 0 : _b.nodeType) === Node.DOCUMENT_FRAGMENT_NODE && n.getRootNode().host)
      shadowHost = n.getRootNode().host;
    return shadowHost;
  }
  function getRootShadowHost(n) {
    let rootShadowHost = n;
    let shadowHost;
    while (shadowHost = getShadowHost(rootShadowHost))
      rootShadowHost = shadowHost;
    return rootShadowHost;
  }
  function shadowHostInDom(n) {
    const doc = n.ownerDocument;
    if (!doc)
      return false;
    const shadowHost = getRootShadowHost(n);
    return doc.contains(shadowHost);
  }
  function inDom(n) {
    const doc = n.ownerDocument;
    if (!doc)
      return false;
    return doc.contains(n) || shadowHostInDom(n);
  }

  var EventType = /* @__PURE__ */ ((EventType2) => {
    EventType2[EventType2["DomContentLoaded"] = 0] = "DomContentLoaded";
    EventType2[EventType2["Load"] = 1] = "Load";
    EventType2[EventType2["FullSnapshot"] = 2] = "FullSnapshot";
    EventType2[EventType2["IncrementalSnapshot"] = 3] = "IncrementalSnapshot";
    EventType2[EventType2["Meta"] = 4] = "Meta";
    EventType2[EventType2["Custom"] = 5] = "Custom";
    EventType2[EventType2["Plugin"] = 6] = "Plugin";
    return EventType2;
  })(EventType || {});
  var IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {
    IncrementalSource2[IncrementalSource2["Mutation"] = 0] = "Mutation";
    IncrementalSource2[IncrementalSource2["MouseMove"] = 1] = "MouseMove";
    IncrementalSource2[IncrementalSource2["MouseInteraction"] = 2] = "MouseInteraction";
    IncrementalSource2[IncrementalSource2["Scroll"] = 3] = "Scroll";
    IncrementalSource2[IncrementalSource2["ViewportResize"] = 4] = "ViewportResize";
    IncrementalSource2[IncrementalSource2["Input"] = 5] = "Input";
    IncrementalSource2[IncrementalSource2["TouchMove"] = 6] = "TouchMove";
    IncrementalSource2[IncrementalSource2["MediaInteraction"] = 7] = "MediaInteraction";
    IncrementalSource2[IncrementalSource2["StyleSheetRule"] = 8] = "StyleSheetRule";
    IncrementalSource2[IncrementalSource2["CanvasMutation"] = 9] = "CanvasMutation";
    IncrementalSource2[IncrementalSource2["Font"] = 10] = "Font";
    IncrementalSource2[IncrementalSource2["Log"] = 11] = "Log";
    IncrementalSource2[IncrementalSource2["Drag"] = 12] = "Drag";
    IncrementalSource2[IncrementalSource2["StyleDeclaration"] = 13] = "StyleDeclaration";
    IncrementalSource2[IncrementalSource2["Selection"] = 14] = "Selection";
    IncrementalSource2[IncrementalSource2["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet";
    return IncrementalSource2;
  })(IncrementalSource || {});
  var MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {
    MouseInteractions2[MouseInteractions2["MouseUp"] = 0] = "MouseUp";
    MouseInteractions2[MouseInteractions2["MouseDown"] = 1] = "MouseDown";
    MouseInteractions2[MouseInteractions2["Click"] = 2] = "Click";
    MouseInteractions2[MouseInteractions2["ContextMenu"] = 3] = "ContextMenu";
    MouseInteractions2[MouseInteractions2["DblClick"] = 4] = "DblClick";
    MouseInteractions2[MouseInteractions2["Focus"] = 5] = "Focus";
    MouseInteractions2[MouseInteractions2["Blur"] = 6] = "Blur";
    MouseInteractions2[MouseInteractions2["TouchStart"] = 7] = "TouchStart";
    MouseInteractions2[MouseInteractions2["TouchMove_Departed"] = 8] = "TouchMove_Departed";
    MouseInteractions2[MouseInteractions2["TouchEnd"] = 9] = "TouchEnd";
    MouseInteractions2[MouseInteractions2["TouchCancel"] = 10] = "TouchCancel";
    return MouseInteractions2;
  })(MouseInteractions || {});
  var PointerTypes = /* @__PURE__ */ ((PointerTypes2) => {
    PointerTypes2[PointerTypes2["Mouse"] = 0] = "Mouse";
    PointerTypes2[PointerTypes2["Pen"] = 1] = "Pen";
    PointerTypes2[PointerTypes2["Touch"] = 2] = "Touch";
    return PointerTypes2;
  })(PointerTypes || {});
  var CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {
    CanvasContext2[CanvasContext2["2D"] = 0] = "2D";
    CanvasContext2[CanvasContext2["WebGL"] = 1] = "WebGL";
    CanvasContext2[CanvasContext2["WebGL2"] = 2] = "WebGL2";
    return CanvasContext2;
  })(CanvasContext || {});
  var MediaInteractions = /* @__PURE__ */ ((MediaInteractions2) => {
    MediaInteractions2[MediaInteractions2["Play"] = 0] = "Play";
    MediaInteractions2[MediaInteractions2["Pause"] = 1] = "Pause";
    MediaInteractions2[MediaInteractions2["Seeked"] = 2] = "Seeked";
    MediaInteractions2[MediaInteractions2["VolumeChange"] = 3] = "VolumeChange";
    MediaInteractions2[MediaInteractions2["RateChange"] = 4] = "RateChange";
    return MediaInteractions2;
  })(MediaInteractions || {});

  function isNodeInLinkedList(n) {
    return "__ln" in n;
  }
  class DoubleLinkedList {
    constructor() {
      this.length = 0;
      this.head = null;
    }
    get(position) {
      if (position >= this.length) {
        throw new Error("Position outside of list range");
      }
      let current = this.head;
      for (let index = 0; index < position; index++) {
        current = (current == null ? void 0 : current.next) || null;
      }
      return current;
    }
    addNode(n) {
      const node = {
        value: n,
        previous: null,
        next: null
      };
      n.__ln = node;
      if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {
        const current = n.previousSibling.__ln.next;
        node.next = current;
        node.previous = n.previousSibling.__ln;
        n.previousSibling.__ln.next = node;
        if (current) {
          current.previous = node;
        }
      } else if (n.nextSibling && isNodeInLinkedList(n.nextSibling) && n.nextSibling.__ln.previous) {
        const current = n.nextSibling.__ln.previous;
        node.previous = current;
        node.next = n.nextSibling.__ln;
        n.nextSibling.__ln.previous = node;
        if (current) {
          current.next = node;
        }
      } else {
        if (this.head) {
          this.head.previous = node;
        }
        node.next = this.head;
        this.head = node;
      }
      this.length++;
    }
    removeNode(n) {
      const current = n.__ln;
      if (!this.head) {
        return;
      }
      if (!current.previous) {
        this.head = current.next;
        if (this.head) {
          this.head.previous = null;
        }
      } else {
        current.previous.next = current.next;
        if (current.next) {
          current.next.previous = current.previous;
        }
      }
      if (n.__ln) {
        delete n.__ln;
      }
      this.length--;
    }
  }
  const moveKey = (id, parentId) => `${id}@${parentId}`;
  class MutationBuffer {
    constructor() {
      this.frozen = false;
      this.locked = false;
      this.texts = [];
      this.attributes = [];
      this.removes = [];
      this.mapRemoves = [];
      this.movedMap = {};
      this.addedSet = /* @__PURE__ */ new Set();
      this.movedSet = /* @__PURE__ */ new Set();
      this.droppedSet = /* @__PURE__ */ new Set();
      this.processMutations = (mutations) => {
        mutations.forEach(this.processMutation);
        this.emit();
      };
      this.emit = () => {
        if (this.frozen || this.locked) {
          return;
        }
        const adds = [];
        const addList = new DoubleLinkedList();
        const getNextId = (n) => {
          let ns = n;
          let nextId = IGNORED_NODE;
          while (nextId === IGNORED_NODE) {
            ns = ns && ns.nextSibling;
            nextId = ns && this.mirror.getId(ns);
          }
          return nextId;
        };
        const pushAdd = (n) => {
          if (!n.parentNode || !inDom(n)) {
            return;
          }
          const parentId = isShadowRoot(n.parentNode) ? this.mirror.getId(getShadowHost(n)) : this.mirror.getId(n.parentNode);
          const nextId = getNextId(n);
          if (parentId === -1 || nextId === -1) {
            return addList.addNode(n);
          }
          const sn = serializeNodeWithId(n, {
            doc: this.doc,
            mirror: this.mirror,
            blockClass: this.blockClass,
            blockSelector: this.blockSelector,
            maskTextClass: this.maskTextClass,
            maskTextSelector: this.maskTextSelector,
            skipChild: true,
            newlyAddedElement: true,
            inlineStylesheet: this.inlineStylesheet,
            maskInputOptions: this.maskInputOptions,
            maskTextFn: this.maskTextFn,
            maskInputFn: this.maskInputFn,
            slimDOMOptions: this.slimDOMOptions,
            dataURLOptions: this.dataURLOptions,
            recordCanvas: this.recordCanvas,
            inlineImages: this.inlineImages,
            onSerialize: (currentN) => {
              if (isSerializedIframe(currentN, this.mirror)) {
                this.iframeManager.addIframe(currentN);
              }
              if (isSerializedStylesheet(currentN, this.mirror)) {
                this.stylesheetManager.trackLinkElement(currentN);
              }
              if (hasShadowRoot(n)) {
                this.shadowDomManager.addShadowRoot(n.shadowRoot, this.doc);
              }
            },
            onIframeLoad: (iframe, childSn) => {
              this.iframeManager.attachIframe(iframe, childSn);
              this.shadowDomManager.observeAttachShadow(iframe);
            },
            onStylesheetLoad: (link, childSn) => {
              this.stylesheetManager.attachLinkElement(link, childSn);
            }
          });
          if (sn) {
            adds.push({
              parentId,
              nextId,
              node: sn
            });
          }
        };
        while (this.mapRemoves.length) {
          this.mirror.removeNodeFromMap(this.mapRemoves.shift());
        }
        for (const n of this.movedSet) {
          if (isParentRemoved(this.removes, n, this.mirror) && !this.movedSet.has(n.parentNode)) {
            continue;
          }
          pushAdd(n);
        }
        for (const n of this.addedSet) {
          if (!isAncestorInSet(this.droppedSet, n) && !isParentRemoved(this.removes, n, this.mirror)) {
            pushAdd(n);
          } else if (isAncestorInSet(this.movedSet, n)) {
            pushAdd(n);
          } else {
            this.droppedSet.add(n);
          }
        }
        let candidate = null;
        while (addList.length) {
          let node = null;
          if (candidate) {
            const parentId = this.mirror.getId(candidate.value.parentNode);
            const nextId = getNextId(candidate.value);
            if (parentId !== -1 && nextId !== -1) {
              node = candidate;
            }
          }
          if (!node) {
            for (let index = addList.length - 1; index >= 0; index--) {
              const _node = addList.get(index);
              if (_node) {
                const parentId = this.mirror.getId(_node.value.parentNode);
                const nextId = getNextId(_node.value);
                if (nextId === -1)
                  continue;
                else if (parentId !== -1) {
                  node = _node;
                  break;
                } else {
                  const unhandledNode = _node.value;
                  if (unhandledNode.parentNode && unhandledNode.parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
                    const shadowHost = unhandledNode.parentNode.host;
                    const parentId2 = this.mirror.getId(shadowHost);
                    if (parentId2 !== -1) {
                      node = _node;
                      break;
                    }
                  }
                }
              }
            }
          }
          if (!node) {
            while (addList.head) {
              addList.removeNode(addList.head.value);
            }
            break;
          }
          candidate = node.previous;
          addList.removeNode(node.value);
          pushAdd(node.value);
        }
        const payload = {
          texts: this.texts.map((text) => ({
            id: this.mirror.getId(text.node),
            value: text.value
          })).filter((text) => this.mirror.has(text.id)),
          attributes: this.attributes.map((attribute) => ({
            id: this.mirror.getId(attribute.node),
            attributes: attribute.attributes
          })).filter((attribute) => this.mirror.has(attribute.id)),
          removes: this.removes,
          adds
        };
        if (!payload.texts.length && !payload.attributes.length && !payload.removes.length && !payload.adds.length) {
          return;
        }
        this.texts = [];
        this.attributes = [];
        this.removes = [];
        this.addedSet = /* @__PURE__ */ new Set();
        this.movedSet = /* @__PURE__ */ new Set();
        this.droppedSet = /* @__PURE__ */ new Set();
        this.movedMap = {};
        this.mutationCb(payload);
      };
      this.processMutation = (m) => {
        if (isIgnored(m.target, this.mirror)) {
          return;
        }
        switch (m.type) {
          case "characterData": {
            const value = m.target.textContent;
            if (!isBlocked(m.target, this.blockClass, this.blockSelector, false) && value !== m.oldValue) {
              this.texts.push({
                value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector) && value ? this.maskTextFn ? this.maskTextFn(value) : value.replace(/[\S]/g, "*") : value,
                node: m.target
              });
            }
            break;
          }
          case "attributes": {
            const target = m.target;
            let attributeName = m.attributeName;
            let value = m.target.getAttribute(attributeName);
            if (attributeName === "value") {
              const type = getInputType(target);
              value = maskInputValue({
                element: target,
                maskInputOptions: this.maskInputOptions,
                tagName: target.tagName,
                type,
                value,
                maskInputFn: this.maskInputFn
              });
            }
            if (isBlocked(m.target, this.blockClass, this.blockSelector, false) || value === m.oldValue) {
              return;
            }
            let item = this.attributes.find((a) => a.node === m.target);
            if (target.tagName === "IFRAME" && attributeName === "src" && !this.keepIframeSrcFn(value)) {
              if (!target.contentDocument) {
                attributeName = "rr_src";
              } else {
                return;
              }
            }
            if (!item) {
              item = {
                node: m.target,
                attributes: {}
              };
              this.attributes.push(item);
            }
            if (attributeName === "type" && target.tagName === "INPUT" && (m.oldValue || "").toLowerCase() === "password") {
              target.setAttribute("data-rr-is-password", "true");
            }
            if (attributeName === "style") {
              const old = this.doc.createElement("span");
              if (m.oldValue) {
                old.setAttribute("style", m.oldValue);
              }
              if (item.attributes.style === void 0 || item.attributes.style === null) {
                item.attributes.style = {};
              }
              const styleObj = item.attributes.style;
              for (const pname of Array.from(target.style)) {
                const newValue = target.style.getPropertyValue(pname);
                const newPriority = target.style.getPropertyPriority(pname);
                if (newValue !== old.style.getPropertyValue(pname) || newPriority !== old.style.getPropertyPriority(pname)) {
                  if (newPriority === "") {
                    styleObj[pname] = newValue;
                  } else {
                    styleObj[pname] = [newValue, newPriority];
                  }
                }
              }
              for (const pname of Array.from(old.style)) {
                if (target.style.getPropertyValue(pname) === "") {
                  styleObj[pname] = false;
                }
              }
            } else if (!ignoreAttribute(target.tagName, attributeName)) {
              item.attributes[attributeName] = transformAttribute(this.doc, target.tagName, attributeName, value);
            }
            break;
          }
          case "childList": {
            if (isBlocked(m.target, this.blockClass, this.blockSelector, true))
              return;
            m.addedNodes.forEach((n) => this.genAdds(n, m.target));
            m.removedNodes.forEach((n) => {
              const nodeId = this.mirror.getId(n);
              const parentId = isShadowRoot(m.target) ? this.mirror.getId(m.target.host) : this.mirror.getId(m.target);
              if (isBlocked(m.target, this.blockClass, this.blockSelector, false) || isIgnored(n, this.mirror) || !isSerialized(n, this.mirror)) {
                return;
              }
              if (this.addedSet.has(n)) {
                deepDelete(this.addedSet, n);
                this.droppedSet.add(n);
              } else if (this.addedSet.has(m.target) && nodeId === -1) ; else if (isAncestorRemoved(m.target, this.mirror)) ; else if (this.movedSet.has(n) && this.movedMap[moveKey(nodeId, parentId)]) {
                deepDelete(this.movedSet, n);
              } else {
                this.removes.push({
                  parentId,
                  id: nodeId,
                  isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target) ? true : void 0
                });
              }
              this.mapRemoves.push(n);
            });
            break;
          }
        }
      };
      this.genAdds = (n, target) => {
        if (this.processedNodeManager.inOtherBuffer(n, this))
          return;
        if (this.mirror.hasNode(n)) {
          if (isIgnored(n, this.mirror)) {
            return;
          }
          this.movedSet.add(n);
          let targetId = null;
          if (target && this.mirror.hasNode(target)) {
            targetId = this.mirror.getId(target);
          }
          if (targetId && targetId !== -1) {
            this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;
          }
        } else {
          this.addedSet.add(n);
          this.droppedSet.delete(n);
        }
        if (!isBlocked(n, this.blockClass, this.blockSelector, false)) {
          n.childNodes.forEach((childN) => this.genAdds(childN));
          if (hasShadowRoot(n)) {
            n.shadowRoot.childNodes.forEach((childN) => {
              this.processedNodeManager.add(childN, this);
              this.genAdds(childN, n);
            });
          }
        }
      };
    }
    init(options) {
      [
        "mutationCb",
        "blockClass",
        "blockSelector",
        "maskTextClass",
        "maskTextSelector",
        "inlineStylesheet",
        "maskInputOptions",
        "maskTextFn",
        "maskInputFn",
        "keepIframeSrcFn",
        "recordCanvas",
        "inlineImages",
        "slimDOMOptions",
        "dataURLOptions",
        "doc",
        "mirror",
        "iframeManager",
        "stylesheetManager",
        "shadowDomManager",
        "canvasManager",
        "processedNodeManager"
      ].forEach((key) => {
        this[key] = options[key];
      });
    }
    freeze() {
      this.frozen = true;
      this.canvasManager.freeze();
    }
    unfreeze() {
      this.frozen = false;
      this.canvasManager.unfreeze();
      this.emit();
    }
    isFrozen() {
      return this.frozen;
    }
    lock() {
      this.locked = true;
      this.canvasManager.lock();
    }
    unlock() {
      this.locked = false;
      this.canvasManager.unlock();
      this.emit();
    }
    reset() {
      this.shadowDomManager.reset();
      this.canvasManager.reset();
    }
  }
  function deepDelete(addsSet, n) {
    addsSet.delete(n);
    n.childNodes.forEach((childN) => deepDelete(addsSet, childN));
  }
  function isParentRemoved(removes, n, mirror) {
    if (removes.length === 0)
      return false;
    return _isParentRemoved(removes, n, mirror);
  }
  function _isParentRemoved(removes, n, mirror) {
    const { parentNode } = n;
    if (!parentNode) {
      return false;
    }
    const parentId = mirror.getId(parentNode);
    if (removes.some((r) => r.id === parentId)) {
      return true;
    }
    return _isParentRemoved(removes, parentNode, mirror);
  }
  function isAncestorInSet(set, n) {
    if (set.size === 0)
      return false;
    return _isAncestorInSet(set, n);
  }
  function _isAncestorInSet(set, n) {
    const { parentNode } = n;
    if (!parentNode) {
      return false;
    }
    if (set.has(parentNode)) {
      return true;
    }
    return _isAncestorInSet(set, parentNode);
  }

  let errorHandler$1;
  function registerErrorHandler(handler) {
    errorHandler$1 = handler;
  }
  function unregisterErrorHandler() {
    errorHandler$1 = void 0;
  }
  const callbackWrapper = (cb) => {
    if (!errorHandler$1) {
      return cb;
    }
    const rrwebWrapped = (...rest) => {
      try {
        return cb(...rest);
      } catch (error) {
        if (errorHandler$1 && errorHandler$1(error) === true) {
          return;
        }
        throw error;
      }
    };
    return rrwebWrapped;
  };

  var __defProp$2 = Object.defineProperty;
  var __defProps$2 = Object.defineProperties;
  var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
  var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
  var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
  var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
  var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  var __spreadValues$2 = (a, b) => {
    for (var prop in b || (b = {}))
      if (__hasOwnProp$3.call(b, prop))
        __defNormalProp$2(a, prop, b[prop]);
    if (__getOwnPropSymbols$3)
      for (var prop of __getOwnPropSymbols$3(b)) {
        if (__propIsEnum$3.call(b, prop))
          __defNormalProp$2(a, prop, b[prop]);
      }
    return a;
  };
  var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
  const mutationBuffers = [];
  function getEventTarget(event) {
    try {
      if ("composedPath" in event) {
        const path = event.composedPath();
        if (path.length) {
          return path[0];
        }
      } else if ("path" in event && event.path.length) {
        return event.path[0];
      }
      return event.target;
    } catch (e) {
      return event.target;
    }
  }
  function initMutationObserver(options, rootEl) {
    var _a, _b;
    const mutationBuffer = new MutationBuffer();
    mutationBuffers.push(mutationBuffer);
    mutationBuffer.init(options);
    let mutationObserverCtor = window.MutationObserver || window.__rrMutationObserver;
    const angularZoneSymbol = (_b = (_a = window == null ? void 0 : window.Zone) == null ? void 0 : _a.__symbol__) == null ? void 0 : _b.call(_a, "MutationObserver");
    if (angularZoneSymbol && window[angularZoneSymbol]) {
      mutationObserverCtor = window[angularZoneSymbol];
    }
    const observer = new mutationObserverCtor(callbackWrapper(mutationBuffer.processMutations.bind(mutationBuffer)));
    observer.observe(rootEl, {
      attributes: true,
      attributeOldValue: true,
      characterData: true,
      characterDataOldValue: true,
      childList: true,
      subtree: true
    });
    return observer;
  }
  function initMoveObserver({
    mousemoveCb,
    sampling,
    doc,
    mirror
  }) {
    if (sampling.mousemove === false) {
      return () => {
      };
    }
    const threshold = typeof sampling.mousemove === "number" ? sampling.mousemove : 50;
    const callbackThreshold = typeof sampling.mousemoveCallback === "number" ? sampling.mousemoveCallback : 500;
    let positions = [];
    let timeBaseline;
    const wrappedCb = throttle(callbackWrapper((source) => {
      const totalOffset = Date.now() - timeBaseline;
      mousemoveCb(positions.map((p) => {
        p.timeOffset -= totalOffset;
        return p;
      }), source);
      positions = [];
      timeBaseline = null;
    }), callbackThreshold);
    const updatePosition = callbackWrapper(throttle(callbackWrapper((evt) => {
      const target = getEventTarget(evt);
      const { clientX, clientY } = legacy_isTouchEvent(evt) ? evt.changedTouches[0] : evt;
      if (!timeBaseline) {
        timeBaseline = Date.now();
      }
      positions.push({
        x: clientX,
        y: clientY,
        id: mirror.getId(target),
        timeOffset: Date.now() - timeBaseline
      });
      wrappedCb(typeof DragEvent !== "undefined" && evt instanceof DragEvent ? IncrementalSource.Drag : evt instanceof MouseEvent ? IncrementalSource.MouseMove : IncrementalSource.TouchMove);
    }), threshold, {
      trailing: false
    }));
    const handlers = [
      on("mousemove", updatePosition, doc),
      on("touchmove", updatePosition, doc),
      on("drag", updatePosition, doc)
    ];
    return callbackWrapper(() => {
      handlers.forEach((h) => h());
    });
  }
  function initMouseInteractionObserver({
    mouseInteractionCb,
    doc,
    mirror,
    blockClass,
    blockSelector,
    sampling
  }) {
    if (sampling.mouseInteraction === false) {
      return () => {
      };
    }
    const disableMap = sampling.mouseInteraction === true || sampling.mouseInteraction === void 0 ? {} : sampling.mouseInteraction;
    const handlers = [];
    let currentPointerType = null;
    const getHandler = (eventKey) => {
      return (event) => {
        const target = getEventTarget(event);
        if (isBlocked(target, blockClass, blockSelector, true)) {
          return;
        }
        let pointerType = null;
        let thisEventKey = eventKey;
        if ("pointerType" in event) {
          switch (event.pointerType) {
            case "mouse":
              pointerType = PointerTypes.Mouse;
              break;
            case "touch":
              pointerType = PointerTypes.Touch;
              break;
            case "pen":
              pointerType = PointerTypes.Pen;
              break;
          }
          if (pointerType === PointerTypes.Touch) {
            if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {
              thisEventKey = "TouchStart";
            } else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {
              thisEventKey = "TouchEnd";
            }
          } else if (pointerType === PointerTypes.Pen) ;
        } else if (legacy_isTouchEvent(event)) {
          pointerType = PointerTypes.Touch;
        }
        if (pointerType !== null) {
          currentPointerType = pointerType;
          if (thisEventKey.startsWith("Touch") && pointerType === PointerTypes.Touch || thisEventKey.startsWith("Mouse") && pointerType === PointerTypes.Mouse) {
            pointerType = null;
          }
        } else if (MouseInteractions[eventKey] === MouseInteractions.Click) {
          pointerType = currentPointerType;
          currentPointerType = null;
        }
        const e = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;
        if (!e) {
          return;
        }
        const id = mirror.getId(target);
        const { clientX, clientY } = e;
        callbackWrapper(mouseInteractionCb)(__spreadValues$2({
          type: MouseInteractions[thisEventKey],
          id,
          x: clientX,
          y: clientY
        }, pointerType !== null && { pointerType }));
      };
    };
    Object.keys(MouseInteractions).filter((key) => Number.isNaN(Number(key)) && !key.endsWith("_Departed") && disableMap[key] !== false).forEach((eventKey) => {
      let eventName = eventKey.toLowerCase();
      const handler = getHandler(eventKey);
      if (window.PointerEvent) {
        switch (MouseInteractions[eventKey]) {
          case MouseInteractions.MouseDown:
          case MouseInteractions.MouseUp:
            eventName = eventName.replace("mouse", "pointer");
            break;
          case MouseInteractions.TouchStart:
          case MouseInteractions.TouchEnd:
            return;
        }
      }
      handlers.push(on(eventName, handler, doc));
    });
    return callbackWrapper(() => {
      handlers.forEach((h) => h());
    });
  }
  function initScrollObserver({
    scrollCb,
    doc,
    mirror,
    blockClass,
    blockSelector,
    sampling
  }) {
    const updatePosition = callbackWrapper(throttle(callbackWrapper((evt) => {
      const target = getEventTarget(evt);
      if (!target || isBlocked(target, blockClass, blockSelector, true)) {
        return;
      }
      const id = mirror.getId(target);
      if (target === doc && doc.defaultView) {
        const scrollLeftTop = getWindowScroll(doc.defaultView);
        scrollCb({
          id,
          x: scrollLeftTop.left,
          y: scrollLeftTop.top
        });
      } else {
        scrollCb({
          id,
          x: target.scrollLeft,
          y: target.scrollTop
        });
      }
    }), sampling.scroll || 100));
    return on("scroll", updatePosition, doc);
  }
  function initViewportResizeObserver({
    viewportResizeCb
  }) {
    let lastH = -1;
    let lastW = -1;
    const updateDimension = callbackWrapper(throttle(callbackWrapper(() => {
      const height = getWindowHeight();
      const width = getWindowWidth();
      if (lastH !== height || lastW !== width) {
        viewportResizeCb({
          width: Number(width),
          height: Number(height)
        });
        lastH = height;
        lastW = width;
      }
    }), 200));
    return on("resize", updateDimension, window);
  }
  function wrapEventWithUserTriggeredFlag(v, enable) {
    const value = __spreadValues$2({}, v);
    if (!enable)
      delete value.userTriggered;
    return value;
  }
  const INPUT_TAGS = ["INPUT", "TEXTAREA", "SELECT"];
  const lastInputValueMap =  window.WeakMap!==undefined?new WeakMap():null;
  function initInputObserver({
    inputCb,
    doc,
    mirror,
    blockClass,
    blockSelector,
    ignoreClass,
    maskInputOptions,
    maskInputFn,
    sampling,
    userTriggeredOnInput
  }) {
    function eventHandler(event) {
      let target = getEventTarget(event);
      const userTriggered = event.isTrusted;
      const tagName = target && target.tagName;
      if (target && tagName === "OPTION") {
        target = target.parentElement;
      }
      if (!target || !tagName || INPUT_TAGS.indexOf(tagName) < 0 || isBlocked(target, blockClass, blockSelector, true)) {
        return;
      }
      if (target.classList.contains(ignoreClass)) {
        return;
      }
      let text = target.value;
      let isChecked = false;
      const type = getInputType(target) || "";
      if (type === "radio" || type === "checkbox") {
        isChecked = target.checked;
      } else if (maskInputOptions[tagName.toLowerCase()] || maskInputOptions[type]) {
        text = maskInputValue({
          element: target,
          maskInputOptions,
          tagName,
          type,
          value: text,
          maskInputFn
        });
      }
      cbWithDedup(target, callbackWrapper(wrapEventWithUserTriggeredFlag)({ text, isChecked, userTriggered }, userTriggeredOnInput));
      const name = target.name;
      if (type === "radio" && name && isChecked) {
        doc.querySelectorAll(`input[type="radio"][name="${name}"]`).forEach((el) => {
          if (el !== target) {
            cbWithDedup(el, callbackWrapper(wrapEventWithUserTriggeredFlag)({
              text: el.value,
              isChecked: !isChecked,
              userTriggered: false
            }, userTriggeredOnInput));
          }
        });
      }
    }
    function cbWithDedup(target, v) {
      if(lastInputValueMap===null){
        return
      }
      const lastInputValue = lastInputValueMap.get(target);
      if (!lastInputValue || lastInputValue.text !== v.text || lastInputValue.isChecked !== v.isChecked) {
        lastInputValueMap.set(target, v);
        const id = mirror.getId(target);
        callbackWrapper(inputCb)(__spreadProps$2(__spreadValues$2({}, v), {
          id
        }));
      }
    }
    const events = sampling.input === "last" ? ["change"] : ["input", "change"];
    const handlers = events.map((eventName) => on(eventName, callbackWrapper(eventHandler), doc));
    const currentWindow = doc.defaultView;
    if (!currentWindow) {
      return () => {
        handlers.forEach((h) => h());
      };
    }
    const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, "value");
    const hookProperties = [
      [currentWindow.HTMLInputElement.prototype, "value"],
      [currentWindow.HTMLInputElement.prototype, "checked"],
      [currentWindow.HTMLSelectElement.prototype, "value"],
      [currentWindow.HTMLTextAreaElement.prototype, "value"],
      [currentWindow.HTMLSelectElement.prototype, "selectedIndex"],
      [currentWindow.HTMLOptionElement.prototype, "selected"]
    ];
    if (propertyDescriptor && propertyDescriptor.set) {
      handlers.push(...hookProperties.map((p) => hookSetter(p[0], p[1], {
        set() {
          callbackWrapper(eventHandler)({
            target: this,
            isTrusted: false
          });
        }
      }, false, currentWindow)));
    }
    return callbackWrapper(() => {
      handlers.forEach((h) => h());
    });
  }
  function getNestedCSSRulePositions(rule) {
    const positions = [];
    function recurse(childRule, pos) {
      if (hasNestedCSSRule("CSSGroupingRule") && childRule.parentRule instanceof CSSGroupingRule || hasNestedCSSRule("CSSMediaRule") && childRule.parentRule instanceof CSSMediaRule || hasNestedCSSRule("CSSSupportsRule") && childRule.parentRule instanceof CSSSupportsRule || hasNestedCSSRule("CSSConditionRule") && childRule.parentRule instanceof CSSConditionRule) {
        const rules = Array.from(childRule.parentRule.cssRules);
        const index = rules.indexOf(childRule);
        pos.unshift(index);
      } else if (childRule.parentStyleSheet) {
        const rules = Array.from(childRule.parentStyleSheet.cssRules);
        const index = rules.indexOf(childRule);
        pos.unshift(index);
      }
      return pos;
    }
    return recurse(rule, positions);
  }
  function getIdAndStyleId(sheet, mirror, styleMirror) {
    let id, styleId;
    if (!sheet)
      return {};
    if (sheet.ownerNode)
      id = mirror.getId(sheet.ownerNode);
    else
      styleId = styleMirror.getId(sheet);
    return {
      styleId,
      id
    };
  }
  function initStyleSheetObserver({ styleSheetRuleCb, mirror, stylesheetManager }, { win }) {
    if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {
      return () => {
      };
    }
    const insertRule = win.CSSStyleSheet.prototype.insertRule;
    win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {
      apply: callbackWrapper((target, thisArg, argumentsList) => {
        const [rule, index] = argumentsList;
        const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);
        if (id && id !== -1 || styleId && styleId !== -1) {
          styleSheetRuleCb({
            id,
            styleId,
            adds: [{ rule, index }]
          });
        }
        return target.apply(thisArg, argumentsList);
      })
    });
    const deleteRule = win.CSSStyleSheet.prototype.deleteRule;
    win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {
      apply: callbackWrapper((target, thisArg, argumentsList) => {
        const [index] = argumentsList;
        const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);
        if (id && id !== -1 || styleId && styleId !== -1) {
          styleSheetRuleCb({
            id,
            styleId,
            removes: [{ index }]
          });
        }
        return target.apply(thisArg, argumentsList);
      })
    });
    let replace;
    if (win.CSSStyleSheet.prototype.replace) {
      replace = win.CSSStyleSheet.prototype.replace;
      win.CSSStyleSheet.prototype.replace = new Proxy(replace, {
        apply: callbackWrapper((target, thisArg, argumentsList) => {
          const [text] = argumentsList;
          const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);
          if (id && id !== -1 || styleId && styleId !== -1) {
            styleSheetRuleCb({
              id,
              styleId,
              replace: text
            });
          }
          return target.apply(thisArg, argumentsList);
        })
      });
    }
    let replaceSync;
    if (win.CSSStyleSheet.prototype.replaceSync) {
      replaceSync = win.CSSStyleSheet.prototype.replaceSync;
      win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {
        apply: callbackWrapper((target, thisArg, argumentsList) => {
          const [text] = argumentsList;
          const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);
          if (id && id !== -1 || styleId && styleId !== -1) {
            styleSheetRuleCb({
              id,
              styleId,
              replaceSync: text
            });
          }
          return target.apply(thisArg, argumentsList);
        })
      });
    }
    const supportedNestedCSSRuleTypes = {};
    if (canMonkeyPatchNestedCSSRule("CSSGroupingRule")) {
      supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;
    } else {
      if (canMonkeyPatchNestedCSSRule("CSSMediaRule")) {
        supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;
      }
      if (canMonkeyPatchNestedCSSRule("CSSConditionRule")) {
        supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;
      }
      if (canMonkeyPatchNestedCSSRule("CSSSupportsRule")) {
        supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;
      }
    }
    const unmodifiedFunctions = {};
    Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {
      unmodifiedFunctions[typeKey] = {
        insertRule: type.prototype.insertRule,
        deleteRule: type.prototype.deleteRule
      };
      type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, {
        apply: callbackWrapper((target, thisArg, argumentsList) => {
          const [rule, index] = argumentsList;
          const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);
          if (id && id !== -1 || styleId && styleId !== -1) {
            styleSheetRuleCb({
              id,
              styleId,
              adds: [
                {
                  rule,
                  index: [
                    ...getNestedCSSRulePositions(thisArg),
                    index || 0
                  ]
                }
              ]
            });
          }
          return target.apply(thisArg, argumentsList);
        })
      });
      type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, {
        apply: callbackWrapper((target, thisArg, argumentsList) => {
          const [index] = argumentsList;
          const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);
          if (id && id !== -1 || styleId && styleId !== -1) {
            styleSheetRuleCb({
              id,
              styleId,
              removes: [
                { index: [...getNestedCSSRulePositions(thisArg), index] }
              ]
            });
          }
          return target.apply(thisArg, argumentsList);
        })
      });
    });
    return callbackWrapper(() => {
      win.CSSStyleSheet.prototype.insertRule = insertRule;
      win.CSSStyleSheet.prototype.deleteRule = deleteRule;
      replace && (win.CSSStyleSheet.prototype.replace = replace);
      replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);
      Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {
        type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;
        type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;
      });
    });
  }
  function initAdoptedStyleSheetObserver({
    mirror,
    stylesheetManager
  }, host) {
    var _a, _b, _c;
    let hostId = null;
    if (host.nodeName === "#document")
      hostId = mirror.getId(host);
    else
      hostId = mirror.getId(host.host);
    const patchTarget = host.nodeName === "#document" ? (_a = host.defaultView) == null ? void 0 : _a.Document : (_c = (_b = host.ownerDocument) == null ? void 0 : _b.defaultView) == null ? void 0 : _c.ShadowRoot;
    const originalPropertyDescriptor = Object.getOwnPropertyDescriptor(patchTarget == null ? void 0 : patchTarget.prototype, "adoptedStyleSheets");
    if (hostId === null || hostId === -1 || !patchTarget || !originalPropertyDescriptor)
      return () => {
      };
    Object.defineProperty(host, "adoptedStyleSheets", {
      configurable: originalPropertyDescriptor.configurable,
      enumerable: originalPropertyDescriptor.enumerable,
      get() {
        var _a2;
        return (_a2 = originalPropertyDescriptor.get) == null ? void 0 : _a2.call(this);
      },
      set(sheets) {
        var _a2;
        const result = (_a2 = originalPropertyDescriptor.set) == null ? void 0 : _a2.call(this, sheets);
        if (hostId !== null && hostId !== -1) {
          try {
            stylesheetManager.adoptStyleSheets(sheets, hostId);
          } catch (e) {
          }
        }
        return result;
      }
    });
    return callbackWrapper(() => {
      Object.defineProperty(host, "adoptedStyleSheets", {
        configurable: originalPropertyDescriptor.configurable,
        enumerable: originalPropertyDescriptor.enumerable,
        get: originalPropertyDescriptor.get,
        set: originalPropertyDescriptor.set
      });
    });
  }
  function initStyleDeclarationObserver({
    styleDeclarationCb,
    mirror,
    ignoreCSSAttributes,
    stylesheetManager
  }, { win }) {
    const setProperty = win.CSSStyleDeclaration.prototype.setProperty;
    win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {
      apply: callbackWrapper((target, thisArg, argumentsList) => {
        var _a;
        const [property, value, priority] = argumentsList;
        if (ignoreCSSAttributes.has(property)) {
          return setProperty.apply(thisArg, [property, value, priority]);
        }
        const { id, styleId } = getIdAndStyleId((_a = thisArg.parentRule) == null ? void 0 : _a.parentStyleSheet, mirror, stylesheetManager.styleMirror);
        if (id && id !== -1 || styleId && styleId !== -1) {
          styleDeclarationCb({
            id,
            styleId,
            set: {
              property,
              value,
              priority
            },
            index: getNestedCSSRulePositions(thisArg.parentRule)
          });
        }
        return target.apply(thisArg, argumentsList);
      })
    });
    const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;
    win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {
      apply: callbackWrapper((target, thisArg, argumentsList) => {
        var _a;
        const [property] = argumentsList;
        if (ignoreCSSAttributes.has(property)) {
          return removeProperty.apply(thisArg, [property]);
        }
        const { id, styleId } = getIdAndStyleId((_a = thisArg.parentRule) == null ? void 0 : _a.parentStyleSheet, mirror, stylesheetManager.styleMirror);
        if (id && id !== -1 || styleId && styleId !== -1) {
          styleDeclarationCb({
            id,
            styleId,
            remove: {
              property
            },
            index: getNestedCSSRulePositions(thisArg.parentRule)
          });
        }
        return target.apply(thisArg, argumentsList);
      })
    });
    return callbackWrapper(() => {
      win.CSSStyleDeclaration.prototype.setProperty = setProperty;
      win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;
    });
  }
  function initMediaInteractionObserver({
    mediaInteractionCb,
    blockClass,
    blockSelector,
    mirror,
    sampling
  }) {
    const handler = callbackWrapper((type) => throttle(callbackWrapper((event) => {
      const target = getEventTarget(event);
      if (!target || isBlocked(target, blockClass, blockSelector, true)) {
        return;
      }
      const { currentTime, volume, muted, playbackRate } = target;
      mediaInteractionCb({
        type,
        id: mirror.getId(target),
        currentTime,
        volume:0,
        muted:true,
        playbackRate
      });
    }), sampling.media || 500));
    const handlers = [
      on("play", handler(MediaInteractions.Play)),
      on("pause", handler(MediaInteractions.Pause)),
      on("seeked", handler(MediaInteractions.Seeked)),
      on("volumechange", handler(MediaInteractions.VolumeChange)),
      on("ratechange", handler(MediaInteractions.RateChange))
    ];
    return callbackWrapper(() => {
      handlers.forEach((h) => h());
    });
  }
  function initFontObserver({ fontCb, doc }) {
    const win = doc.defaultView;
    if (!win) {
      return () => {
      };
    }
    const handlers = [];
    const fontMap = /* @__PURE__ */ new WeakMap();
    const originalFontFace = win.FontFace;
    win.FontFace = function FontFace(family, source, descriptors) {
      const fontFace = new originalFontFace(family, source, descriptors);
      fontMap.set(fontFace, {
        family,
        buffer: typeof source !== "string",
        descriptors,
        fontSource: typeof source === "string" ? source : JSON.stringify(Array.from(new Uint8Array(source)))
      });
      return fontFace;
    };
    const restoreHandler = patch(doc.fonts, "add", function(original) {
      return function(fontFace) {
        setTimeout(callbackWrapper(() => {
          const p = fontMap.get(fontFace);
          if (p) {
            fontCb(p);
            fontMap.delete(fontFace);
          }
        }), 0);
        return original.apply(this, [fontFace]);
      };
    });
    handlers.push(() => {
      win.FontFace = originalFontFace;
    });
    handlers.push(restoreHandler);
    return callbackWrapper(() => {
      handlers.forEach((h) => h());
    });
  }
  function initSelectionObserver(param) {
    const { doc, mirror, blockClass, blockSelector, selectionCb } = param;
    let collapsed = true;
    const updateSelection = callbackWrapper(() => {
      const selection = doc.getSelection();
      if (!selection || collapsed && (selection == null ? void 0 : selection.isCollapsed))
        return;
      collapsed = selection.isCollapsed || false;
      const ranges = [];
      const count = selection.rangeCount || 0;
      for (let i = 0; i < count; i++) {
        const range = selection.getRangeAt(i);
        const { startContainer, startOffset, endContainer, endOffset } = range;
        const blocked = isBlocked(startContainer, blockClass, blockSelector, true) || isBlocked(endContainer, blockClass, blockSelector, true);
        if (blocked)
          continue;
        ranges.push({
          start: mirror.getId(startContainer),
          startOffset,
          end: mirror.getId(endContainer),
          endOffset
        });
      }
      selectionCb({ ranges });
    });
    updateSelection();
    return on("selectionchange", updateSelection);
  }
  function mergeHooks(o, hooks) {
    const {
      mutationCb,
      mousemoveCb,
      mouseInteractionCb,
      scrollCb,
      viewportResizeCb,
      inputCb,
      mediaInteractionCb,
      styleSheetRuleCb,
      styleDeclarationCb,
      canvasMutationCb,
      fontCb,
      selectionCb
    } = o;
    o.mutationCb = (...p) => {
      if (hooks.mutation) {
        hooks.mutation(...p);
      }
      mutationCb(...p);
    };
    o.mousemoveCb = (...p) => {
      if (hooks.mousemove) {
        hooks.mousemove(...p);
      }
      mousemoveCb(...p);
    };
    o.mouseInteractionCb = (...p) => {
      if (hooks.mouseInteraction) {
        hooks.mouseInteraction(...p);
      }
      mouseInteractionCb(...p);
    };
    o.scrollCb = (...p) => {
      if (hooks.scroll) {
        hooks.scroll(...p);
      }
      scrollCb(...p);
    };
    o.viewportResizeCb = (...p) => {
      if (hooks.viewportResize) {
        hooks.viewportResize(...p);
      }
      viewportResizeCb(...p);
    };
    o.inputCb = (...p) => {
      if (hooks.input) {
        hooks.input(...p);
      }
      inputCb(...p);
    };
    o.mediaInteractionCb = (...p) => {
      if (hooks.mediaInteaction) {
        hooks.mediaInteaction(...p);
      }
      mediaInteractionCb(...p);
    };
    o.styleSheetRuleCb = (...p) => {
      if (hooks.styleSheetRule) {
        hooks.styleSheetRule(...p);
      }
      styleSheetRuleCb(...p);
    };
    o.styleDeclarationCb = (...p) => {
      if (hooks.styleDeclaration) {
        hooks.styleDeclaration(...p);
      }
      styleDeclarationCb(...p);
    };
    o.canvasMutationCb = (...p) => {
      if (hooks.canvasMutation) {
        hooks.canvasMutation(...p);
      }
      canvasMutationCb(...p);
    };
    o.fontCb = (...p) => {
      if (hooks.font) {
        hooks.font(...p);
      }
      fontCb(...p);
    };
    o.selectionCb = (...p) => {
      if (hooks.selection) {
        hooks.selection(...p);
      }
      selectionCb(...p);
    };
  }
  function initObservers(o, hooks = {}) {
    const currentWindow = o.doc.defaultView;
    if (!currentWindow) {
      return () => {
      };
    }
    mergeHooks(o, hooks);
    const mutationObserver = initMutationObserver(o, o.doc);
    const mousemoveHandler = initMoveObserver(o);
    const mouseInteractionHandler = initMouseInteractionObserver(o);
    const scrollHandler = initScrollObserver(o);
    const viewportResizeHandler = initViewportResizeObserver(o);
    const inputHandler = initInputObserver(o);
    const mediaInteractionHandler = initMediaInteractionObserver(o);
    const styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });
    const adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);
    const styleDeclarationObserver = initStyleDeclarationObserver(o, {
      win: currentWindow
    });
    const fontObserver = o.collectFonts ? initFontObserver(o) : () => {
    };
    const selectionObserver = initSelectionObserver(o);
    const pluginHandlers = [];
    for (const plugin of o.plugins) {
      pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));
    }
    return callbackWrapper(() => {
      mutationBuffers.forEach((b) => b.reset());
      mutationObserver.disconnect();
      mousemoveHandler();
      mouseInteractionHandler();
      scrollHandler();
      viewportResizeHandler();
      inputHandler();
      mediaInteractionHandler();
      styleSheetObserver();
      adoptedStyleSheetObserver();
      styleDeclarationObserver();
      fontObserver();
      selectionObserver();
      pluginHandlers.forEach((h) => h());
    });
  }
  function hasNestedCSSRule(prop) {
    return typeof window[prop] !== "undefined";
  }
  function canMonkeyPatchNestedCSSRule(prop) {
    return Boolean(typeof window[prop] !== "undefined" && window[prop].prototype && "insertRule" in window[prop].prototype && "deleteRule" in window[prop].prototype);
  }

  class CrossOriginIframeMirror {
    constructor(generateIdFn) {
      this.generateIdFn = generateIdFn;
      this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();
      this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();
    }
    getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {
      const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);
      const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);
      let id = idToRemoteIdMap.get(remoteId);
      if (!id) {
        id = this.generateIdFn();
        idToRemoteIdMap.set(remoteId, id);
        remoteIdToIdMap.set(id, remoteId);
      }
      return id;
    }
    getIds(iframe, remoteId) {
      const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);
      const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
      return remoteId.map((id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap));
    }
    getRemoteId(iframe, id, map) {
      const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);
      if (typeof id !== "number")
        return id;
      const remoteId = remoteIdToIdMap.get(id);
      if (!remoteId)
        return -1;
      return remoteId;
    }
    getRemoteIds(iframe, ids) {
      const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
      return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));
    }
    reset(iframe) {
      if (!iframe) {
        this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();
        this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();
        return;
      }
      this.iframeIdToRemoteIdMap.delete(iframe);
      this.iframeRemoteIdToIdMap.delete(iframe);
    }
    getIdToRemoteIdMap(iframe) {
      let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);
      if (!idToRemoteIdMap) {
        idToRemoteIdMap = /* @__PURE__ */ new Map();
        this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);
      }
      return idToRemoteIdMap;
    }
    getRemoteIdToIdMap(iframe) {
      let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);
      if (!remoteIdToIdMap) {
        remoteIdToIdMap = /* @__PURE__ */ new Map();
        this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);
      }
      return remoteIdToIdMap;
    }
  }

  class IframeManager {
    constructor(options) {
      this.iframes = /* @__PURE__ */ new WeakMap();
      this.crossOriginIframeMap = /* @__PURE__ */ new WeakMap();
      this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);
      this.crossOriginIframeRootIdMap = /* @__PURE__ */ new WeakMap();
      this.mutationCb = options.mutationCb;
      this.wrappedEmit = options.wrappedEmit;
      this.stylesheetManager = options.stylesheetManager;
      this.recordCrossOriginIframes = options.recordCrossOriginIframes;
      this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));
      this.mirror = options.mirror;
      if (this.recordCrossOriginIframes) {
        window.addEventListener("message", this.handleMessage.bind(this));
      }
    }
    addIframe(iframeEl) {
      this.iframes.set(iframeEl, true);
      if (iframeEl.contentWindow)
        this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);
    }
    addLoadListener(cb) {
      this.loadListener = cb;
    }
    attachIframe(iframeEl, childSn) {
      var _a;
      this.mutationCb({
        adds: [
          {
            parentId: this.mirror.getId(iframeEl),
            nextId: null,
            node: childSn
          }
        ],
        removes: [],
        texts: [],
        attributes: [],
        isAttachIframe: true
      });
      (_a = this.loadListener) == null ? void 0 : _a.call(this, iframeEl);
      if (iframeEl.contentDocument && iframeEl.contentDocument.adoptedStyleSheets && iframeEl.contentDocument.adoptedStyleSheets.length > 0)
        this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));
    }
    handleMessage(message) {
      const crossOriginMessageEvent = message;
      if (crossOriginMessageEvent.data.type !== "rrweb" || crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin)
        return;
      const iframeSourceWindow = message.source;
      if (!iframeSourceWindow)
        return;
      const iframeEl = this.crossOriginIframeMap.get(message.source);
      if (!iframeEl)
        return;
      const transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event);
      if (transformedEvent)
        this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout);
    }
    transformCrossOriginEvent(iframeEl, e) {
      var _a;
      switch (e.type) {
        case EventType.FullSnapshot: {
          this.crossOriginIframeMirror.reset(iframeEl);
          this.crossOriginIframeStyleMirror.reset(iframeEl);
          this.replaceIdOnNode(e.data.node, iframeEl);
          const rootId = e.data.node.id;
          this.crossOriginIframeRootIdMap.set(iframeEl, rootId);
          this.patchRootIdOnNode(e.data.node, rootId);
          return {
            timestamp: e.timestamp,
            type: EventType.IncrementalSnapshot,
            data: {
              source: IncrementalSource.Mutation,
              adds: [
                {
                  parentId: this.mirror.getId(iframeEl),
                  nextId: null,
                  node: e.data.node
                }
              ],
              removes: [],
              texts: [],
              attributes: [],
              isAttachIframe: true
            }
          };
        }
        case EventType.Meta:
        case EventType.Load:
        case EventType.DomContentLoaded: {
          return false;
        }
        case EventType.Plugin: {
          return e;
        }
        case EventType.Custom: {
          this.replaceIds(e.data.payload, iframeEl, ["id", "parentId", "previousId", "nextId"]);
          return e;
        }
        case EventType.IncrementalSnapshot: {
          switch (e.data.source) {
            case IncrementalSource.Mutation: {
              e.data.adds.forEach((n) => {
                this.replaceIds(n, iframeEl, [
                  "parentId",
                  "nextId",
                  "previousId"
                ]);
                this.replaceIdOnNode(n.node, iframeEl);
                const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);
                rootId && this.patchRootIdOnNode(n.node, rootId);
              });
              e.data.removes.forEach((n) => {
                this.replaceIds(n, iframeEl, ["parentId", "id"]);
              });
              e.data.attributes.forEach((n) => {
                this.replaceIds(n, iframeEl, ["id"]);
              });
              e.data.texts.forEach((n) => {
                this.replaceIds(n, iframeEl, ["id"]);
              });
              return e;
            }
            case IncrementalSource.Drag:
            case IncrementalSource.TouchMove:
            case IncrementalSource.MouseMove: {
              e.data.positions.forEach((p) => {
                this.replaceIds(p, iframeEl, ["id"]);
              });
              return e;
            }
            case IncrementalSource.ViewportResize: {
              return false;
            }
            case IncrementalSource.MediaInteraction:
            case IncrementalSource.MouseInteraction:
            case IncrementalSource.Scroll:
            case IncrementalSource.CanvasMutation:
            case IncrementalSource.Input: {
              this.replaceIds(e.data, iframeEl, ["id"]);
              return e;
            }
            case IncrementalSource.StyleSheetRule:
            case IncrementalSource.StyleDeclaration: {
              this.replaceIds(e.data, iframeEl, ["id"]);
              this.replaceStyleIds(e.data, iframeEl, ["styleId"]);
              return e;
            }
            case IncrementalSource.Font: {
              return e;
            }
            case IncrementalSource.Selection: {
              e.data.ranges.forEach((range) => {
                this.replaceIds(range, iframeEl, ["start", "end"]);
              });
              return e;
            }
            case IncrementalSource.AdoptedStyleSheet: {
              this.replaceIds(e.data, iframeEl, ["id"]);
              this.replaceStyleIds(e.data, iframeEl, ["styleIds"]);
              (_a = e.data.styles) == null ? void 0 : _a.forEach((style) => {
                this.replaceStyleIds(style, iframeEl, ["styleId"]);
              });
              return e;
            }
          }
        }
      }
    }
    replace(iframeMirror, obj, iframeEl, keys) {
      for (const key of keys) {
        if (!Array.isArray(obj[key]) && typeof obj[key] !== "number")
          continue;
        if (Array.isArray(obj[key])) {
          obj[key] = iframeMirror.getIds(iframeEl, obj[key]);
        } else {
          obj[key] = iframeMirror.getId(iframeEl, obj[key]);
        }
      }
      return obj;
    }
    replaceIds(obj, iframeEl, keys) {
      return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);
    }
    replaceStyleIds(obj, iframeEl, keys) {
      return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);
    }
    replaceIdOnNode(node, iframeEl) {
      this.replaceIds(node, iframeEl, ["id", "rootId"]);
      if ("childNodes" in node) {
        node.childNodes.forEach((child) => {
          this.replaceIdOnNode(child, iframeEl);
        });
      }
    }
    patchRootIdOnNode(node, rootId) {
      if (node.type !== NodeType.Document && !node.rootId)
        node.rootId = rootId;
      if ("childNodes" in node) {
        node.childNodes.forEach((child) => {
          this.patchRootIdOnNode(child, rootId);
        });
      }
    }
  }

  var __defProp$1 = Object.defineProperty;
  var __defProps$1 = Object.defineProperties;
  var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
  var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
  var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
  var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
  var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  var __spreadValues$1 = (a, b) => {
    for (var prop in b || (b = {}))
      if (__hasOwnProp$2.call(b, prop))
        __defNormalProp$1(a, prop, b[prop]);
    if (__getOwnPropSymbols$2)
      for (var prop of __getOwnPropSymbols$2(b)) {
        if (__propIsEnum$2.call(b, prop))
          __defNormalProp$1(a, prop, b[prop]);
      }
    return a;
  };
  var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
  class ShadowDomManager {
    constructor(options) {
      this.shadowDoms = /* @__PURE__ */ new WeakSet();
      this.restoreHandlers = [];
      this.mutationCb = options.mutationCb;
      this.scrollCb = options.scrollCb;
      this.bypassOptions = options.bypassOptions;
      this.mirror = options.mirror;
      this.init();
    }
    init() {
      this.reset();
      this.patchAttachShadow(Element, document);
    }
    addShadowRoot(shadowRoot, doc) {
      if (!isNativeShadowDom(shadowRoot))
        return;
      if (this.shadowDoms.has(shadowRoot))
        return;
      this.shadowDoms.add(shadowRoot);
      const observer = initMutationObserver(__spreadProps$1(__spreadValues$1({}, this.bypassOptions), {
        doc,
        mutationCb: this.mutationCb,
        mirror: this.mirror,
        shadowDomManager: this
      }), shadowRoot);
      this.restoreHandlers.push(() => observer.disconnect());
      this.restoreHandlers.push(initScrollObserver(__spreadProps$1(__spreadValues$1({}, this.bypassOptions), {
        scrollCb: this.scrollCb,
        doc: shadowRoot,
        mirror: this.mirror
      })));
      setTimeout(() => {
        if (shadowRoot.adoptedStyleSheets && shadowRoot.adoptedStyleSheets.length > 0)
          this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets, this.mirror.getId(shadowRoot.host));
        this.restoreHandlers.push(initAdoptedStyleSheetObserver({
          mirror: this.mirror,
          stylesheetManager: this.bypassOptions.stylesheetManager
        }, shadowRoot));
      }, 0);
    }
    observeAttachShadow(iframeElement) {
      if (!iframeElement.contentWindow || !iframeElement.contentDocument)
        return;
      this.patchAttachShadow(iframeElement.contentWindow.Element, iframeElement.contentDocument);
    }
    patchAttachShadow(element, doc) {
      const manager = this;
      this.restoreHandlers.push(patch(element.prototype, "attachShadow", function(original) {
        return function(option) {
          const shadowRoot = original.call(this, option);
          if (this.shadowRoot && inDom(this))
            manager.addShadowRoot(this.shadowRoot, doc);
          return shadowRoot;
        };
      }));
    }
    reset() {
      this.restoreHandlers.forEach((handler) => {
        try {
          handler();
        } catch (e) {
        }
      });
      this.restoreHandlers = [];
      this.shadowDoms = /* @__PURE__ */ new WeakSet();
    }
  }

  /*
   * base64-arraybuffer 1.0.1 <https://github.com/niklasvh/base64-arraybuffer>
   * Copyright (c) 2021 Niklas von Hertzen <https://hertzen.com>
   * Released under MIT License
   */
  var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  // Use a lookup table to find the index.
  var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
  for (var i = 0; i < chars.length; i++) {
      lookup[chars.charCodeAt(i)] = i;
  }
  var encode = function (arraybuffer) {
      var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';
      for (i = 0; i < len; i += 3) {
          base64 += chars[bytes[i] >> 2];
          base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
          base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
          base64 += chars[bytes[i + 2] & 63];
      }
      if (len % 3 === 2) {
          base64 = base64.substring(0, base64.length - 1) + '=';
      }
      else if (len % 3 === 1) {
          base64 = base64.substring(0, base64.length - 2) + '==';
      }
      return base64;
  };

  const canvasVarMap = /* @__PURE__ */ new Map();
  function variableListFor(ctx, ctor) {
    let contextMap = canvasVarMap.get(ctx);
    if (!contextMap) {
      contextMap = /* @__PURE__ */ new Map();
      canvasVarMap.set(ctx, contextMap);
    }
    if (!contextMap.has(ctor)) {
      contextMap.set(ctor, []);
    }
    return contextMap.get(ctor);
  }
  const saveWebGLVar = (value, win, ctx) => {
    if (!value || !(isInstanceOfWebGLObject(value, win) || typeof value === "object"))
      return;
    const name = value.constructor.name;
    const list = variableListFor(ctx, name);
    let index = list.indexOf(value);
    if (index === -1) {
      index = list.length;
      list.push(value);
    }
    return index;
  };
  function serializeArg(value, win, ctx) {
    if (value instanceof Array) {
      return value.map((arg) => serializeArg(arg, win, ctx));
    } else if (value === null) {
      return value;
    } else if (value instanceof Float32Array || value instanceof Float64Array || value instanceof Int32Array || value instanceof Uint32Array || value instanceof Uint8Array || value instanceof Uint16Array || value instanceof Int16Array || value instanceof Int8Array || value instanceof Uint8ClampedArray) {
      const name = value.constructor.name;
      return {
        rr_type: name,
        args: [Object.values(value)]
      };
    } else if (value instanceof ArrayBuffer) {
      const name = value.constructor.name;
      const base64 = encode(value);
      return {
        rr_type: name,
        base64
      };
    } else if (value instanceof DataView) {
      const name = value.constructor.name;
      return {
        rr_type: name,
        args: [
          serializeArg(value.buffer, win, ctx),
          value.byteOffset,
          value.byteLength
        ]
      };
    } else if (value instanceof HTMLImageElement) {
      const name = value.constructor.name;
      const { src } = value;
      return {
        rr_type: name,
        src
      };
    } else if (value instanceof HTMLCanvasElement) {
      const name = "HTMLImageElement";
      const src = value.toDataURL();
      return {
        rr_type: name,
        src
      };
    } else if (value instanceof ImageData) {
      const name = value.constructor.name;
      return {
        rr_type: name,
        args: [serializeArg(value.data, win, ctx), value.width, value.height]
      };
    } else if (isInstanceOfWebGLObject(value, win) || typeof value === "object") {
      const name = value.constructor.name;
      const index = saveWebGLVar(value, win, ctx);
      return {
        rr_type: name,
        index
      };
    }
    return value;
  }
  const serializeArgs = (args, win, ctx) => {
    return [...args].map((arg) => serializeArg(arg, win, ctx));
  };
  const isInstanceOfWebGLObject = (value, win) => {
    const webGLConstructorNames = [
      "WebGLActiveInfo",
      "WebGLBuffer",
      "WebGLFramebuffer",
      "WebGLProgram",
      "WebGLRenderbuffer",
      "WebGLShader",
      "WebGLShaderPrecisionFormat",
      "WebGLTexture",
      "WebGLUniformLocation",
      "WebGLVertexArrayObject",
      "WebGLVertexArrayObjectOES"
    ];
    const supportedWebGLConstructorNames = webGLConstructorNames.filter((name) => typeof win[name] === "function");
    return Boolean(supportedWebGLConstructorNames.find((name) => value instanceof win[name]));
  };

  function initCanvas2DMutationObserver(cb, win, blockClass2, blockSelector) {
    const handlers = [];
    const props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);
    for (const prop of props2D) {
      try {
        if (typeof win.CanvasRenderingContext2D.prototype[prop] !== "function") {
          continue;
        }
        const restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function(original) {
          return function(...args) {
            if (!isBlocked(this.canvas, blockClass2, blockSelector, true)) {
              setTimeout(() => {
                const recordArgs = serializeArgs([...args], win, this);
                cb(this.canvas, {
                  type: CanvasContext["2D"],
                  property: prop,
                  args: recordArgs
                });
              }, 0);
            }
            return original.apply(this, args);
          };
        });
        handlers.push(restoreHandler);
      } catch (e) {
        const hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, {
          set(v) {
            cb(this.canvas, {
              type: CanvasContext["2D"],
              property: prop,
              args: [v],
              setter: true
            });
          }
        });
        handlers.push(hookHandler);
      }
    }
    return () => {
      handlers.forEach((h) => h());
    };
  }

  function initCanvasContextObserver(win, blockClass, blockSelector) {
    const handlers = [];
    try {
      const restoreHandler = patch(win.HTMLCanvasElement.prototype, "getContext", function(original) {
        return function(contextType, ...args) {
          if (!isBlocked(this, blockClass, blockSelector, true)) {
            if (!("__context" in this))
              this.__context = contextType;
          }
          return original.apply(this, [contextType, ...args]);
        };
      });
      handlers.push(restoreHandler);
    } catch (e) {
      console.error("failed to patch HTMLCanvasElement.prototype.getContext");
    }
    return () => {
      handlers.forEach((h) => h());
    };
  }

  function patchGLPrototype(prototype, type, cb, blockClass2, blockSelector, mirror, win) {
    const handlers = [];
    const props = Object.getOwnPropertyNames(prototype);
    for (const prop of props) {
      if ([
        "isContextLost",
        "canvas",
        "drawingBufferWidth",
        "drawingBufferHeight"
      ].includes(prop)) {
        continue;
      }
      try {
        if (typeof prototype[prop] !== "function") {
          continue;
        }
        const restoreHandler = patch(prototype, prop, function(original) {
          return function(...args) {
            const result = original.apply(this, args);
            saveWebGLVar(result, win, this);
            if (!isBlocked(this.canvas, blockClass2, blockSelector, true)) {
              const recordArgs = serializeArgs([...args], win, this);
              const mutation = {
                type,
                property: prop,
                args: recordArgs
              };
              cb(this.canvas, mutation);
            }
            return result;
          };
        });
        handlers.push(restoreHandler);
      } catch (e) {
        const hookHandler = hookSetter(prototype, prop, {
          set(v) {
            cb(this.canvas, {
              type,
              property: prop,
              args: [v],
              setter: true
            });
          }
        });
        handlers.push(hookHandler);
      }
    }
    return handlers;
  }
  function initCanvasWebGLMutationObserver(cb, win, blockClass2, blockSelector, mirror) {
    const handlers = [];
    handlers.push(...patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass2, blockSelector, mirror, win));
    if (typeof win.WebGL2RenderingContext !== "undefined") {
      handlers.push(...patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass2, blockSelector, mirror, win));
    }
    return () => {
      handlers.forEach((h) => h());
    };
  }

  function decodeBase64(base64, enableUnicode) {
      var binaryString = atob(base64);
      return binaryString;
  }

  function createURL(base64, sourcemapArg, enableUnicodeArg) {
      var source = decodeBase64(base64);
      var start = source.indexOf('\n', 10) + 1;
      var body = source.substring(start) + ('');
      var blob = new Blob([body], { type: 'application/javascript' });
      return URL.createObjectURL(blob);
  }

  function createBase64WorkerFactory(base64, sourcemapArg, enableUnicodeArg) {
      var url;
      return function WorkerFactory(options) {
          url = url || createURL(base64);
          return new Worker(url, options);
      };
  }

  var WorkerFactory = createBase64WorkerFactory('Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewogICAgJ3VzZSBzdHJpY3QnOwoKICAgIC8qCiAgICAgKiBiYXNlNjQtYXJyYXlidWZmZXIgMS4wLjEgPGh0dHBzOi8vZ2l0aHViLmNvbS9uaWtsYXN2aC9iYXNlNjQtYXJyYXlidWZmZXI+CiAgICAgKiBDb3B5cmlnaHQgKGMpIDIwMjEgTmlrbGFzIHZvbiBIZXJ0emVuIDxodHRwczovL2hlcnR6ZW4uY29tPgogICAgICogUmVsZWFzZWQgdW5kZXIgTUlUIExpY2Vuc2UKICAgICAqLwogICAgdmFyIGNoYXJzID0gJ0FCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU2Nzg5Ky8nOwogICAgLy8gVXNlIGEgbG9va3VwIHRhYmxlIHRvIGZpbmQgdGhlIGluZGV4LgogICAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAndW5kZWZpbmVkJyA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICAgIGZvciAodmFyIGkgPSAwOyBpIDwgY2hhcnMubGVuZ3RoOyBpKyspIHsKICAgICAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogICAgfQogICAgdmFyIGVuY29kZSA9IGZ1bmN0aW9uIChhcnJheWJ1ZmZlcikgewogICAgICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaSwgbGVuID0gYnl0ZXMubGVuZ3RoLCBiYXNlNjQgPSAnJzsKICAgICAgICBmb3IgKGkgPSAwOyBpIDwgbGVuOyBpICs9IDMpIHsKICAgICAgICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2ldID4+IDJdOwogICAgICAgICAgICBiYXNlNjQgKz0gY2hhcnNbKChieXRlc1tpXSAmIDMpIDw8IDQpIHwgKGJ5dGVzW2kgKyAxXSA+PiA0KV07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1soKGJ5dGVzW2kgKyAxXSAmIDE1KSA8PCAyKSB8IChieXRlc1tpICsgMl0gPj4gNildOwogICAgICAgICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaSArIDJdICYgNjNdOwogICAgICAgIH0KICAgICAgICBpZiAobGVuICUgMyA9PT0gMikgewogICAgICAgICAgICBiYXNlNjQgPSBiYXNlNjQuc3Vic3RyaW5nKDAsIGJhc2U2NC5sZW5ndGggLSAxKSArICc9JzsKICAgICAgICB9CiAgICAgICAgZWxzZSBpZiAobGVuICUgMyA9PT0gMSkgewogICAgICAgICAgICBiYXNlNjQgPSBiYXNlNjQuc3Vic3RyaW5nKDAsIGJhc2U2NC5sZW5ndGggLSAyKSArICc9PSc7CiAgICAgICAgfQogICAgICAgIHJldHVybiBiYXNlNjQ7CiAgICB9OwoKICAgIGNvbnN0IGxhc3RCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICAgIGNvbnN0IHRyYW5zcGFyZW50QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgICAgY29uc3QgaWQgPSBgJHt3aWR0aH0tJHtoZWlnaHR9YDsKICAgICAgaWYgKCJPZmZzY3JlZW5DYW52YXMiIGluIGdsb2JhbFRoaXMpIHsKICAgICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpCiAgICAgICAgICByZXR1cm4gdHJhbnNwYXJlbnRCbG9iTWFwLmdldChpZCk7CiAgICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgICBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgICBjb25zdCBibG9iID0gYXdhaXQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOwogICAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgICAgdHJhbnNwYXJlbnRCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsKICAgICAgICByZXR1cm4gYmFzZTY0OwogICAgICB9IGVsc2UgewogICAgICAgIHJldHVybiAiIjsKICAgICAgfQogICAgfQogICAgY29uc3Qgd29ya2VyID0gc2VsZjsKICAgIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICAgIGlmICgiT2Zmc2NyZWVuQ2FudmFzIiBpbiBnbG9iYWxUaGlzKSB7CiAgICAgICAgY29uc3QgeyBpZCwgYml0bWFwLCB3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucyB9ID0gZS5kYXRhOwogICAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zKTsKICAgICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICAgIGNvbnN0IGN0eCA9IG9mZnNjcmVlbi5nZXRDb250ZXh0KCIyZCIpOwogICAgICAgIGN0eC5kcmF3SW1hZ2UoYml0bWFwLCAwLCAwKTsKICAgICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgICBjb25zdCBibG9iID0gYXdhaXQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOwogICAgICAgIGNvbnN0IHR5cGUgPSBibG9iLnR5cGU7CiAgICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgICAgY29uc3QgYmFzZTY0ID0gZW5jb2RlKGFycmF5QnVmZmVyKTsKICAgICAgICBpZiAoIWxhc3RCbG9iTWFwLmhhcyhpZCkgJiYgYXdhaXQgdHJhbnNwYXJlbnRCYXNlNjQgPT09IGJhc2U2NCkgewogICAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgICAgcmV0dXJuIHdvcmtlci5wb3N0TWVzc2FnZSh7IGlkIH0pOwogICAgICAgIH0KICAgICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KQogICAgICAgICAgcmV0dXJuIHdvcmtlci5wb3N0TWVzc2FnZSh7IGlkIH0pOwogICAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgICBpZCwKICAgICAgICAgIHR5cGUsCiAgICAgICAgICBiYXNlNjQsCiAgICAgICAgICB3aWR0aCwKICAgICAgICAgIGhlaWdodAogICAgICAgIH0pOwogICAgICAgIGxhc3RCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsKICAgICAgfSBlbHNlIHsKICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgICAgfQogICAgfTsKCn0pKCk7Cgo=');
  /* eslint-enable */

  var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
  var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
  var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
  var __objRest = (source, exclude) => {
    var target = {};
    for (var prop in source)
      if (__hasOwnProp$1.call(source, prop) && exclude.indexOf(prop) < 0)
        target[prop] = source[prop];
    if (source != null && __getOwnPropSymbols$1)
      for (var prop of __getOwnPropSymbols$1(source)) {
        if (exclude.indexOf(prop) < 0 && __propIsEnum$1.call(source, prop))
          target[prop] = source[prop];
      }
    return target;
  };
  var __async = (__this, __arguments, generator) => {
    return new Promise((resolve, reject) => {
      var fulfilled = (value) => {
        try {
          step(generator.next(value));
        } catch (e) {
          reject(e);
        }
      };
      var rejected = (value) => {
        try {
          step(generator.throw(value));
        } catch (e) {
          reject(e);
        }
      };
      var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
      step((generator = generator.apply(__this, __arguments)).next());
    });
  };
  class CanvasManager {
    constructor(options) {
      this.pendingCanvasMutations = /* @__PURE__ */ new Map();
      this.rafStamps = { latestId: 0, invokeId: null };
      this.frozen = false;
      this.locked = false;
      this.processMutation = (target, mutation) => {
        const newFrame = this.rafStamps.invokeId && this.rafStamps.latestId !== this.rafStamps.invokeId;
        if (newFrame || !this.rafStamps.invokeId)
          this.rafStamps.invokeId = this.rafStamps.latestId;
        if (!this.pendingCanvasMutations.has(target)) {
          this.pendingCanvasMutations.set(target, []);
        }
        this.pendingCanvasMutations.get(target).push(mutation);
      };
      const {
        sampling = "all",
        win,
        blockClass,
        blockSelector,
        recordCanvas,
        dataURLOptions
      } = options;
      this.mutationCb = options.mutationCb;
      this.mirror = options.mirror;
      if (recordCanvas && sampling === "all")
        this.initCanvasMutationObserver(win, blockClass, blockSelector);
      if (recordCanvas && typeof sampling === "number")
        this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, {
          dataURLOptions
        });
    }
    reset() {
      this.pendingCanvasMutations.clear();
      this.resetObservers && this.resetObservers();
    }
    freeze() {
      this.frozen = true;
    }
    unfreeze() {
      this.frozen = false;
    }
    lock() {
      this.locked = true;
    }
    unlock() {
      this.locked = false;
    }
    initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {
      const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector);
      const snapshotInProgressMap = /* @__PURE__ */ new Map();
      const worker = new WorkerFactory();
      worker.onmessage = (e) => {
        const { id } = e.data;
        snapshotInProgressMap.set(id, false);
        if (!("base64" in e.data))
          return;
        const { base64, type, width, height } = e.data;
        this.mutationCb({
          id,
          type: CanvasContext["2D"],
          commands: [
            {
              property: "clearRect",
              args: [0, 0, width, height]
            },
            {
              property: "drawImage",
              args: [
                {
                  rr_type: "ImageBitmap",
                  args: [
                    {
                      rr_type: "Blob",
                      data: [{ rr_type: "ArrayBuffer", base64 }],
                      type
                    }
                  ]
                },
                0,
                0
              ]
            }
          ]
        });
      };
      const timeBetweenSnapshots = 1e3 / fps;
      let lastSnapshotTime = 0;
      let rafId;
      const getCanvas = () => {
        const matchedCanvas = [];
        win.document.querySelectorAll("canvas").forEach((canvas) => {
          if (!isBlocked(canvas, blockClass, blockSelector, true)) {
            matchedCanvas.push(canvas);
          }
        });
        return matchedCanvas;
      };
      const takeCanvasSnapshots = (timestamp) => {
        if (lastSnapshotTime && timestamp - lastSnapshotTime < timeBetweenSnapshots) {
          rafId = requestAnimationFrame(takeCanvasSnapshots);
          return;
        }
        lastSnapshotTime = timestamp;
        getCanvas().forEach((canvas) => __async(this, null, function* () {
          var _a;
          const id = this.mirror.getId(canvas);
          if (snapshotInProgressMap.get(id))
            return;
          snapshotInProgressMap.set(id, true);
          if (["webgl", "webgl2"].includes(canvas.__context)) {
            const context = canvas.getContext(canvas.__context);
            if (((_a = context == null ? void 0 : context.getContextAttributes()) == null ? void 0 : _a.preserveDrawingBuffer) === false) {
              context == null ? void 0 : context.clear(context.COLOR_BUFFER_BIT);
            }
          }
          const bitmap = yield createImageBitmap(canvas);
          worker.postMessage({
            id,
            bitmap,
            width: canvas.width,
            height: canvas.height,
            dataURLOptions: options.dataURLOptions
          }, [bitmap]);
        }));
        rafId = requestAnimationFrame(takeCanvasSnapshots);
      };
      rafId = requestAnimationFrame(takeCanvasSnapshots);
      this.resetObservers = () => {
        canvasContextReset();
        cancelAnimationFrame(rafId);
      };
    }
    initCanvasMutationObserver(win, blockClass, blockSelector) {
      this.startRAFTimestamping();
      this.startPendingCanvasMutationFlusher();
      const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector);
      const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
      const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, this.mirror);
      this.resetObservers = () => {
        canvasContextReset();
        canvas2DReset();
        canvasWebGL1and2Reset();
      };
    }
    startPendingCanvasMutationFlusher() {
      requestAnimationFrame(() => this.flushPendingCanvasMutations());
    }
    startRAFTimestamping() {
      const setLatestRAFTimestamp = (timestamp) => {
        this.rafStamps.latestId = timestamp;
        requestAnimationFrame(setLatestRAFTimestamp);
      };
      requestAnimationFrame(setLatestRAFTimestamp);
    }
    flushPendingCanvasMutations() {
      this.pendingCanvasMutations.forEach((values, canvas) => {
        const id = this.mirror.getId(canvas);
        this.flushPendingCanvasMutationFor(canvas, id);
      });
      requestAnimationFrame(() => this.flushPendingCanvasMutations());
    }
    flushPendingCanvasMutationFor(canvas, id) {
      if (this.frozen || this.locked) {
        return;
      }
      const valuesWithType = this.pendingCanvasMutations.get(canvas);
      if (!valuesWithType || id === -1)
        return;
      const values = valuesWithType.map((value) => {
        const _a = value, rest = __objRest(_a, ["type"]);
        return rest;
      });
      const { type } = valuesWithType[0];
      this.mutationCb({ id, type, commands: values });
      this.pendingCanvasMutations.delete(canvas);
    }
  }

  class StylesheetManager {
    constructor(options) {
      this.trackedLinkElements = /* @__PURE__ */ new WeakSet();
      this.styleMirror = new StyleSheetMirror();
      this.mutationCb = options.mutationCb;
      this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;
    }
    attachLinkElement(linkEl, childSn) {
      if ("_cssText" in childSn.attributes)
        this.mutationCb({
          adds: [],
          removes: [],
          texts: [],
          attributes: [
            {
              id: childSn.id,
              attributes: childSn.attributes
            }
          ]
        });
      this.trackLinkElement(linkEl);
    }
    trackLinkElement(linkEl) {
      if (this.trackedLinkElements.has(linkEl))
        return;
      this.trackedLinkElements.add(linkEl);
      this.trackStylesheetInLinkElement(linkEl);
    }
    adoptStyleSheets(sheets, hostId) {
      if (sheets.length === 0)
        return;
      const adoptedStyleSheetData = {
        id: hostId,
        styleIds: []
      };
      const styles = [];
      for (const sheet of sheets) {
        let styleId;
        if (!this.styleMirror.has(sheet)) {
          styleId = this.styleMirror.add(sheet);
          const rules = Array.from(sheet.rules || CSSRule);
          styles.push({
            styleId,
            rules: rules.map((r, index) => {
              return {
                rule: getCssRuleString(r),
                index
              };
            })
          });
        } else
          styleId = this.styleMirror.getId(sheet);
        adoptedStyleSheetData.styleIds.push(styleId);
      }
      if (styles.length > 0)
        adoptedStyleSheetData.styles = styles;
      this.adoptedStyleSheetCb(adoptedStyleSheetData);
    }
    reset() {
      this.styleMirror.reset();
      this.trackedLinkElements = /* @__PURE__ */ new WeakSet();
    }
    trackStylesheetInLinkElement(linkEl) {
    }
  }

  class ProcessedNodeManager {
    constructor() {
      this.nodeMap = /* @__PURE__ */ new WeakMap();
      this.loop = true;
      this.periodicallyClear();
    }
    periodicallyClear() {
      requestAnimationFrame(() => {
        this.clear();
        if (this.loop)
          this.periodicallyClear();
      });
    }
    inOtherBuffer(node, thisBuffer) {
      const buffers = this.nodeMap.get(node);
      return buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer);
    }
    add(node, buffer) {
      this.nodeMap.set(node, (this.nodeMap.get(node) || /* @__PURE__ */ new Set()).add(buffer));
    }
    clear() {
      this.nodeMap = /* @__PURE__ */ new WeakMap();
    }
    destroy() {
      this.loop = false;
    }
  }

  var __defProp = Object.defineProperty;
  var __defProps = Object.defineProperties;
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  var __hasOwnProp = Object.prototype.hasOwnProperty;
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  var __spreadValues = (a, b) => {
    for (var prop in b || (b = {}))
      if (__hasOwnProp.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    if (__getOwnPropSymbols)
      for (var prop of __getOwnPropSymbols(b)) {
        if (__propIsEnum.call(b, prop))
          __defNormalProp(a, prop, b[prop]);
      }
    return a;
  };
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
  function wrapEvent(e) {
    return __spreadProps(__spreadValues({}, e), {
      timestamp: Date.now()
    });
  }
  let wrappedEmit;
  let takeFullSnapshot;
  let canvasManager;
  let recording = false;
  const mirror = createMirror();
  function record(options = {}) {
    const {
      emit,
      checkoutEveryNms,
      checkoutEveryNth,
      blockClass = "rr-block",
      blockSelector = null,
      ignoreClass = "rr-ignore",
      maskTextClass = "rr-mask",
      maskTextSelector = null,
      inlineStylesheet = true,
      maskAllInputs,
      maskInputOptions: _maskInputOptions,
      slimDOMOptions: _slimDOMOptions,
      maskInputFn,
      maskTextFn,
      hooks,
      packFn,
      sampling = {},
      dataURLOptions = {},
      mousemoveWait,
      recordCanvas = false,
      recordCrossOriginIframes = true,
      recordAfter = options.recordAfter === "DOMContentLoaded" ? options.recordAfter : "load",
      userTriggeredOnInput = false,
      collectFonts = false,
      inlineImages = false,
      plugins,
      keepIframeSrcFn = () => false,
      ignoreCSSAttributes = /* @__PURE__ */ new Set([]),
      errorHandler
    } = options;
    registerErrorHandler(errorHandler);
    const inEmittingFrame = recordCrossOriginIframes ? window.parent === window : true;
    let passEmitsToParent = false;
    if (!inEmittingFrame) {
      try {
        if (window.parent.document) {
          passEmitsToParent = false;
        }
      } catch (e) {
        passEmitsToParent = true;
      }
    }
    if (inEmittingFrame && !emit) {
      throw new Error("emit function is required");
    }
    if (mousemoveWait !== void 0 && sampling.mousemove === void 0) {
      sampling.mousemove = mousemoveWait;
    }
    mirror.reset();
    const maskInputOptions = maskAllInputs === true ? {
      color: true,
      date: true,
      "datetime-local": true,
      email: true,
      month: true,
      number: true,
      range: true,
      search: true,
      tel: true,
      text: true,
      time: true,
      url: true,
      week: true,
      textarea: true,
      select: true,
      password: true
    } : _maskInputOptions !== void 0 ? _maskInputOptions : { password: true };
    const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === "all" ? {
      script: true,
      comment: true,
      headFavicon: true,
      headWhitespace: true,
      headMetaSocial: true,
      headMetaRobots: true,
      headMetaHttpEquiv: true,
      headMetaVerification: true,
      headMetaAuthorship: _slimDOMOptions === "all",
      headMetaDescKeywords: _slimDOMOptions === "all"
    } : _slimDOMOptions ? _slimDOMOptions : {};
    polyfill();
    let lastFullSnapshotEvent;
    let incrementalSnapshotCount = 0;
    const eventProcessor = (e) => {
      for (const plugin of plugins || []) {
        if (plugin.eventProcessor) {
          e = plugin.eventProcessor(e);
        }
      }
      if (packFn && !passEmitsToParent) {
        e = packFn(e);
      }
      return e;
    };
    wrappedEmit = (e, isCheckout) => {
      var _a;
      if (((_a = mutationBuffers[0]) == null ? void 0 : _a.isFrozen()) && e.type !== EventType.FullSnapshot && !(e.type === EventType.IncrementalSnapshot && e.data.source === IncrementalSource.Mutation)) {
        mutationBuffers.forEach((buf) => buf.unfreeze());
      }
      if (inEmittingFrame) {
        emit == null ? void 0 : emit(eventProcessor(e), isCheckout);
      } else if (passEmitsToParent) {
        const message = {
          type: "rrweb",
          event: eventProcessor(e),
          origin: window.location.origin,
          isCheckout
        };
        window.parent.postMessage(message, "*");
      }
      if (e.type === EventType.FullSnapshot) {
        lastFullSnapshotEvent = e;
        incrementalSnapshotCount = 0;
      } else if (e.type === EventType.IncrementalSnapshot) {
        if (e.data.source === IncrementalSource.Mutation && e.data.isAttachIframe) {
          return;
        }
        incrementalSnapshotCount++;
        const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;
        const exceedTime = checkoutEveryNms && e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;
        if (exceedCount || exceedTime) {
          takeFullSnapshot(true);
        }
      }
    };
    const wrappedMutationEmit = (m) => {
      wrappedEmit(wrapEvent({
        type: EventType.IncrementalSnapshot,
        data: __spreadValues({
          source: IncrementalSource.Mutation
        }, m)
      }));
    };
    const wrappedScrollEmit = (p) => wrappedEmit(wrapEvent({
      type: EventType.IncrementalSnapshot,
      data: __spreadValues({
        source: IncrementalSource.Scroll
      }, p)
    }));
    const wrappedCanvasMutationEmit = (p) => wrappedEmit(wrapEvent({
      type: EventType.IncrementalSnapshot,
      data: __spreadValues({
        source: IncrementalSource.CanvasMutation
      }, p)
    }));
    const wrappedAdoptedStyleSheetEmit = (a) => wrappedEmit(wrapEvent({
      type: EventType.IncrementalSnapshot,
      data: __spreadValues({
        source: IncrementalSource.AdoptedStyleSheet
      }, a)
    }));
    const stylesheetManager = new StylesheetManager({
      mutationCb: wrappedMutationEmit,
      adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit
    });
    const iframeManager = new IframeManager({
      mirror,
      mutationCb: wrappedMutationEmit,
      stylesheetManager,
      recordCrossOriginIframes,
      wrappedEmit
    });
    for (const plugin of plugins || []) {
      if (plugin.getMirror)
        plugin.getMirror({
          nodeMirror: mirror,
          crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,
          crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror
        });
    }
    const processedNodeManager = new ProcessedNodeManager();
    canvasManager = new CanvasManager({
      recordCanvas,
      mutationCb: wrappedCanvasMutationEmit,
      win: window,
      blockClass,
      blockSelector,
      mirror,
      sampling: sampling.canvas,
      dataURLOptions
    });
    const shadowDomManager = new ShadowDomManager({
      mutationCb: wrappedMutationEmit,
      scrollCb: wrappedScrollEmit,
      bypassOptions: {
        blockClass,
        blockSelector,
        maskTextClass,
        maskTextSelector,
        inlineStylesheet,
        maskInputOptions,
        dataURLOptions,
        maskTextFn,
        maskInputFn,
        recordCanvas,
        inlineImages,
        sampling,
        slimDOMOptions,
        iframeManager,
        stylesheetManager,
        canvasManager,
        keepIframeSrcFn,
        processedNodeManager
      },
      mirror
    });
    takeFullSnapshot = (isCheckout = false) => {
      wrappedEmit(wrapEvent({
        type: EventType.Meta,
        data: {
          href: window.location.href,
          width: getWindowWidth(),
          height: getWindowHeight()
        }
      }), isCheckout);
      stylesheetManager.reset();
      shadowDomManager.init();
      mutationBuffers.forEach((buf) => buf.lock());
      const node = snapshot(document, {
        mirror,
        blockClass,
        blockSelector,
        maskTextClass,
        maskTextSelector,
        inlineStylesheet,
        maskAllInputs: maskInputOptions,
        maskTextFn,
        slimDOM: slimDOMOptions,
        dataURLOptions,
        recordCanvas,
        inlineImages,
        onSerialize: (n) => {
          if (isSerializedIframe(n, mirror)) {
            iframeManager.addIframe(n);
          }
          if (isSerializedStylesheet(n, mirror)) {
            stylesheetManager.trackLinkElement(n);
          }
          if (hasShadowRoot(n)) {
            shadowDomManager.addShadowRoot(n.shadowRoot, document);
          }
        },
        onIframeLoad: (iframe, childSn) => {
          iframeManager.attachIframe(iframe, childSn);
          shadowDomManager.observeAttachShadow(iframe);
        },
        onStylesheetLoad: (linkEl, childSn) => {
          stylesheetManager.attachLinkElement(linkEl, childSn);
        },
        keepIframeSrcFn
      });
      if (!node) {
        return console.warn("Failed to snapshot the document");
      }
      wrappedEmit(wrapEvent({
        type: EventType.FullSnapshot,
        data: {
          node,
          initialOffset: getWindowScroll(window)
        }
      }), isCheckout);
      mutationBuffers.forEach((buf) => buf.unlock());
      if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)
        stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));
    };
    try {
      const handlers = [];
      const observe = (doc) => {
        var _a;
        return callbackWrapper(initObservers)({
          mutationCb: wrappedMutationEmit,
          mousemoveCb: (positions, source) => wrappedEmit(wrapEvent({
            type: EventType.IncrementalSnapshot,
            data: {
              source,
              positions
            }
          })),
          mouseInteractionCb: (d) => wrappedEmit(wrapEvent({
            type: EventType.IncrementalSnapshot,
            data: __spreadValues({
              source: IncrementalSource.MouseInteraction
            }, d)
          })),
          scrollCb: wrappedScrollEmit,
          viewportResizeCb: (d) => wrappedEmit(wrapEvent({
            type: EventType.IncrementalSnapshot,
            data: __spreadValues({
              source: IncrementalSource.ViewportResize
            }, d)
          })),
          inputCb: (v) => wrappedEmit(wrapEvent({
            type: EventType.IncrementalSnapshot,
            data: __spreadValues({
              source: IncrementalSource.Input
            }, v)
          })),
          mediaInteractionCb: (p) => wrappedEmit(wrapEvent({
            type: EventType.IncrementalSnapshot,
            data: __spreadValues({
              source: IncrementalSource.MediaInteraction
            }, p)
          })),
          styleSheetRuleCb: (r) => wrappedEmit(wrapEvent({
            type: EventType.IncrementalSnapshot,
            data: __spreadValues({
              source: IncrementalSource.StyleSheetRule
            }, r)
          })),
          styleDeclarationCb: (r) => wrappedEmit(wrapEvent({
            type: EventType.IncrementalSnapshot,
            data: __spreadValues({
              source: IncrementalSource.StyleDeclaration
            }, r)
          })),
          canvasMutationCb: wrappedCanvasMutationEmit,
          fontCb: (p) => wrappedEmit(wrapEvent({
            type: EventType.IncrementalSnapshot,
            data: __spreadValues({
              source: IncrementalSource.Font
            }, p)
          })),
          selectionCb: (p) => {
            wrappedEmit(wrapEvent({
              type: EventType.IncrementalSnapshot,
              data: __spreadValues({
                source: IncrementalSource.Selection
              }, p)
            }));
          },
          blockClass,
          ignoreClass,
          maskTextClass,
          maskTextSelector,
          maskInputOptions,
          inlineStylesheet,
          sampling,
          recordCanvas,
          inlineImages,
          userTriggeredOnInput,
          collectFonts,
          doc,
          maskInputFn,
          maskTextFn,
          keepIframeSrcFn,
          blockSelector,
          slimDOMOptions,
          dataURLOptions,
          mirror,
          iframeManager,
          stylesheetManager,
          shadowDomManager,
          processedNodeManager,
          canvasManager,
          ignoreCSSAttributes,
          plugins: ((_a = plugins == null ? void 0 : plugins.filter((p) => p.observer)) == null ? void 0 : _a.map((p) => ({
            observer: p.observer,
            options: p.options,
            callback: (payload) => wrappedEmit(wrapEvent({
              type: EventType.Plugin,
              data: {
                plugin: p.name,
                payload
              }
            }))
          }))) || []
        }, hooks);
      };
      iframeManager.addLoadListener((iframeEl) => {
        try {
          handlers.push(observe(iframeEl.contentDocument));
        } catch (error) {
          console.warn(error);
        }
      });
      const init = () => {
        takeFullSnapshot();
        handlers.push(observe(document));
        recording = true;
      };
      if (document.readyState === "interactive" || document.readyState === "complete") {
        init();
      } else {
        handlers.push(on("DOMContentLoaded", () => {
          wrappedEmit(wrapEvent({
            type: EventType.DomContentLoaded,
            data: {}
          }));
          if (recordAfter === "DOMContentLoaded")
            init();
        }));
        handlers.push(on("load", () => {
          wrappedEmit(wrapEvent({
            type: EventType.Load,
            data: {}
          }));
          if (recordAfter === "load")
            init();
        }, window));
      }
      return () => {
        handlers.forEach((h) => h());
        processedNodeManager.destroy();
        recording = false;
        unregisterErrorHandler();
      };
    } catch (error) {
      console.warn(error);
    }
  }
  record.addCustomEvent = (tag, payload) => {
    if (!recording) {
      throw new Error("please add custom event after start recording");
    }
    wrappedEmit(wrapEvent({
      type: EventType.Custom,
      data: {
        tag,
        payload
      }
    }));
  };
  record.freezePage = () => {
    mutationBuffers.forEach((buf) => buf.freeze());
  };
  record.takeFullSnapshot = (isCheckout) => {
      RecordStart=0;
    if (!recording) {
      //console.warn("please take full snapshot after start recording");
      return
    }
    takeFullSnapshot(isCheckout);
  };
  record.mirror = mirror;
  function compressData(data) {
      const jsonString = JSON.stringify(data);
      const compressedData = pako.gzip(jsonString, { level: 9 }); // 使用最大的压缩级别（level: 9）
      // const base64EncodedData = btoa(String.fromCharCode(...compressedData));
      const base64EncodedData = btoa(new Uint8Array(compressedData).reduce(function (data, byte) {
        return data + String.fromCharCode(byte);
    }, ''));
      return base64EncodedData;
    }
  function RecordDataHandle(UploadAddress,setting){
      if(isDefined(window.stopBonreeRecordUpload)){
        return
      }
      if(RecordEvents.length===0){
          return
      }
      if(RecordStart===0){
        RecordStart=RecordEvents[0].timestamp*1000;
      }
      var formdata = new FormData();
      formdata.append("s",bonreeRUM.getSession());
      formdata.append("v",bonreeRUM&&bonreeRUM.version||"1.0.0");
      formdata.append("mt",String(now()));
      formdata.append("cmt",String(setting.initTime));
      formdata.append("di",JSON.stringify(getDeviceInfo()));
      formdata.append("ai",JSON.stringify({ 
          'ai': setting.appId,
          "av":setting.appVersion||'unknown',
          "an":setting.appName||'unknown',
          "at":4
      }));
      if(setting.dataFusionInfo=='net'){
        formdata.append("dfi",JSON.stringify({"net":"net"}));
      }
      if(RecordStart === 0){
        RecordStart = RecordEvents[0].timestamp * 1000;
        formdata.append("st", RecordStart);
      }else {
        formdata.append("st", RecordStart);
      }
      if(!isDefined(window.bonreeRUM)&&isDefined(window.bonreeRUM.getUserInfo)){
        log("C154");
        return
      }
      if(Object.getOwnPropertyNames(bonreeRUM.getUserInfo()).length!==0){
          formdata.append("ui",JSON.stringify(Object.entries(bonreeRUM.getUserInfo())[0][1]));
      }
      var ud=RecordEvents[RecordEvents.length-1].timestamp*1000-RecordStart;
      formdata.append("ud",ud);
      RecordStart=RecordEvents[RecordEvents.length-1].timestamp*1000;
      formdata.append("wev","2.0.0-alpha.8");
      var BlobData=new Blob([JSON.stringify({wsd:compressData(RecordEvents)})], {type : 'application/json'});
      formdata.append("event",BlobData);
      UploadSessionReplayEvent(formdata,UploadAddress+"?a="+setting.appId+"&brkey="+uuid()+"&d="+getDeviceInfo().di+"&v=2023061901");
  }
  function UploadSessionReplayEvent(body,url){
          if(window.fetch){
              fetch(url,{
                  method:"POST",
                  body:body
              }).then(
                  function(response){
                  if(response!==undefined){
                      RecordEvents=[];
                      return response.json()
                  }
              },function(reson){
                  console.warn("fetch reject:",reson);
              }
              ).catch(function(error){
                  console.warn("fetch reject:",error);
              });
      }
      }
  function BonreeRecord(setting){
      globalData.BonreeRecordState=true;
      function getConfig(sett){
        var _con;
        if(sett instanceof Array){
          sett.forEach(function(value){
            if(value.n==='sessionreplay'){
              _con=value;
            }
          });
        }
        return _con||sett
      }
      var configuration=getConfig(setting.RecordConfiguration || setting.mc);
      /*现在mc下有不同配置,未获取到直接return*/
      if(!isDefined(configuration)){
          return
      }
     var  checkRecordRate=function (rate){
          let random=Math.floor(Math.random()*100);
          return rate<random?false:true
      };
          if(
        isDefined(configuration) 
        && isDefined(configuration.Rate)
        && checkRecordRate(configuration.Rate) 
        || isDefined(configuration) 
        && isDefined(configuration.c)
        && checkRecordRate(configuration.c)){
        if(window.location.protocol==="https:"){
          Replayurl=configuration.UploadHttps || configuration.src&&configuration.src.uas;
        }else {
          Replayurl=configuration.UploadHttp || configuration.src&&configuration.src.ua;
        } 
        window.$bonreeReplayUrl=Replayurl;
        if(isDefined(Replayurl)){
          setInterval(RecordDataHandle,(configuration.UploadCycle || configuration.src&&configuration.src.uc)*1000,Replayurl,setting);
        }
          var AllTextMask={
              emit:function (event){
                  RecordEvents.push(event);
              },
              maskAllInputs:true,
              recordCanvas:true,
              recordCrossOriginIframes:true,
              maskTextSelector:"body",
              maskTextFn:function (textContent){
                  if(textContent.indexOf("\n")===-1){
                       return   "*".repeat(textContent.length)
                  }else {
                       var needToMask=textContent.trim();
                       return textContent.replace(needToMask,"*".repeat(needToMask.length))
                  }
              }
          };
          var InputTextMask={
              emit:function (event){
                  RecordEvents.push(event);
              },
              maskAllInputs:true,
              recordCanvas:true,
              recordCrossOriginIframes:true
          };
          //simple
          if(configuration.src&&configuration.src.sl!==undefined){
              if(configuration.src.sl===1){
                return  record(AllTextMask)
              }else {
                 return record(InputTextMask)
              }
          }
          //full
          if(configuration.Sensitivity!==undefined){
              if(configuration.Sensitivity===1){
                 return record(AllTextMask)
              }else {
                 return record(InputTextMask)
              } 
          }
      }
  }
  BonreeRecord.takeFullSnapshot=record.takeFullSnapshot;

  /*
   * 上报数据协议体结构体对象
   * json 已转化的协议体数据,组包处理完的数据
   * @constructor 协议体构造器
   */
  class Protocol {
      constructor() {
          this.json = {
              'v': bonreeRUM&&bonreeRUM.version||"1.0.0",
              'e': []
          };
      }
  }



  /**
   * 设置协议中的upload监控时间(首次组合数据上报的时间) 「单位us 时间戳」
   * @param {*} timestamp long
   */
  Protocol.prototype.setMonitorTime = function (timestamp) {
      this.json.mt = timestamp;
      return this;
  };

  /**
   * 设置协议中的Config配置初始化的时间 「单位us 时间戳」
   * @param {*} timestamp long
   */
  Protocol.prototype.setConfigTime = function (timestamp) {
      this.json.cmt = timestamp;
      return this;
  };

  /**
   * session 会话
   * @param {*} sessionId 字符串 
   */
  Protocol.prototype.setSessionId = function (sessionId) {
      this.json.s = sessionId;
      return this;
  };

  /**
   * 设置协议中的DeviceInfo 设备信息
   * @param {*} deviceInfo object
   */
  Protocol.prototype.setDeviceInfo = function (deviceInfo) {
      this.json.di = deviceInfo;
      return this;
  };

  /**
   * 设置协议中的AppInfo 应用信息
   * @param {*} appInfo object
   */
  Protocol.prototype.setAppInfo = function (appInfo) {
      this.json.ai = appInfo;
      return this;
  };

  /**
   * 首个设置的有效UserInfo信息的索引（有效指UserInfo中设置了UserID，且有事件使用）。该字段一个会话中最多赋值一次[非必要字段]
   * @param {*} userInfoIndex 字符串 
   */
  Protocol.prototype.setFirstUserInfoIndex = function () {
      const key = globalData.firstUserInfoSetMapKey;
      if (key !== '') {
          this.json.fui = key;
          //上传后重置首个用户信息索引值
          globalData.updateFirstUserInfoSetMapKey('');
      }
      return this;
  };

  /**
   * UserInfo 用户信息 [非必要字段] 使用Key:Value形式记录多个UserInfo,Event中记录Key做对应
   * @param {*} userInfo object
   */
  Protocol.prototype.setUserInfo = function (userInfo) {
      this.json.ui = userInfo;
      return this;
  };

  /**
   * unit session duration 单位upload中会话持续时间，本次最大ent-上次最大ent。「单位us，可能为0」[非空字段]
   * @param {*} sessionDuration long
   */
  Protocol.prototype.setSessionDuration = function (sessionDuration) {
      this.json.usd = sessionDuration;
      return this;
  };

  /**
   * 压入事件对象
   * @param {*} metric 业务指标对象
   */
  Protocol.prototype.pushEventData = function (metric) {
      const event = {
          'k': metric.type,
          'ent': metric.ent,
          'sin': metric.sin,
          'v': metric.data
      };
      if(isDefined(metric.revts)){
          event.revts=metric.revts;
      }
      this.json.e.push(event);
      return this;
  };

  /**
   * 压入事件对象
   * @param {*} metric 业务指标对象
   */
  Protocol.prototype.build = function (metric) {
      return this.json;
  };
  /**
   * @descripe 设置dfi
   * @param {*} data 
   */
  Protocol.prototype.setDataFusionInfo=function(data){
      this.json.dfi={"net":data};
      return this
  };
  /**
   * @descripe 设置sst
   * @param {*} data sst值
   */
  Protocol.prototype.setSessionStartTime=function(data){
      this.json.sst=data;
      return this
  };

  //超时时间
  const TIMEOUT = 30000;
  const uploadDatas=[];
  let uploadFinished=true;
  /** 
   * @descripe 判断是否是首包上报
   **/
  function isFirstUpload(){
    if(GS.sett.isFirstUpload){
      extend(GS.sett,{
        isFirstUpload:0
      });
      return 1
    }
    return 0
  }
  /** 
   * @descripe 拼接上报地址和路径参数
   **/
  function getUrl(params,uid) {
      let url='';
      if(window.location.protocol==='https:'){
          /*走upload请求说明有浏览器配置,两个配置只支持一个是浏览器配置,使用场景也只有一个配置会有上报地址*/
          if(isDefined(GS.sett.uploadAddrHttps)){
            url=GS.sett.uploadAddrHttps;
          }
          if(isDefined(GS.secondSett.uploadAddrHttps)){
            url=GS.secondSett.uploadAddrHttps;
          }
      }else {
        if(isDefined(GS.sett.uploadAddrHttp)){
          url=GS.sett.uploadAddrHttp;
        }
        if(isDefined(GS.secondSett.uploadAddrHttp)){
          url=GS.secondSett.uploadAddrHttp;
        }
      }
      url += '?v=2024041001'; 
      url += '&a=' + params.ai.ai;
      url += '&d=' + params.di.di;
      url += '&mt=' + params.mt;
      url += '&cmt=' + params.cmt;
      url += '&s=' + params.s;
      url += '&brkey='+uid;
      url += '&if='+isFirstUpload();
      if(GS.sett.sm4Config!==undefined&&/^[A-Za-z0-9_-]{1,256}$/.test(GS.sett.sm4Config.identify || GS.sett.sm4Config.identifier)){
        var identify=GS.sett.sm4Config.identify || GS.sett.sm4Config.identifier;
        url+=`&BR-Encryption-Method=sm4:${identify}`;
      }
      if(isDefined(window.bonreeRUM)&&window.bonreeRUM.isPrivate){
        url += '&isp=1';
      }else {
        url += '&isp=0';
      }
      return url
  }

  function post(url, body, onEnd, force,uid) {
    var req;
    // IE8
    if (window.XDomainRequest) {
      req = new window.XDomainRequest();

      req.open('POST', url);
      req.timeout = TIMEOUT;
      req.onload = function () {
        onEnd && onEnd(true);
      };
      req.onerror = req.ontimeout = function () {
        onEnd && onEnd(false);
      };
      delay(function () {
        req.send(body);
      });
      return true
    }

    if (!window.XMLHttpRequest) {
      return false
    }
    req = new window.XMLHttpRequest();
    try {
      req.$$inner = true;
      req.overrideMimeType('text/plain');
      /**
       * Fix:
       * In safari, XMLHttpRequest.timeout cannot be set for synchronous http(s) requests made from the window context.
       */
      req.open('POST', url, true);
      req.setRequestHeader("brkey",uid);
      req.timeout = TIMEOUT;
      req.onreadystatechange = function () {
        if (req.readyState === 4) {
          onEnd && onEnd(req.status === 200);
          handleXHRRes(req);
        }
      };
    } catch (e) {

    }

    {
      req.send(body);
    }

    return true
  }


  /**
  * Fix:
  * Mobile qq in IOS, beacon api will lost the request payload.
  * Do not use beacon API to fix it.
  */
  function isQQEnv() {
    return /\bQQ\b/i.test(navigator.userAgent)
  }
  function handleXHRRes(response){
    uploadFinished=true;
    prePost();
  }
  function prePost(url, body, onEnd, force,uid){
    if(url&&body&&uploadDatas.length<100){
      uploadDatas.push({data:body,uid:uid,url:url});
    }
    if(uploadFinished===true&&uploadDatas.length>0){
      const uploadData=uploadDatas.shift();
      uploadFinished=false;
      post(uploadData.url,uploadData.data,onEnd,true,uploadData.uid);
    }
  }
  function sendUpload(body, force, callback) {
    console.log('react:',body)
    let uid=uuid();
    var url = getUrl(body,uid);
    if (!startWith(url, 'http')) {
      return false
    }
    const useXHR=GS.sett.useXHR||GS.secondSett.useXHR||false;
    // beaconAPI仅告知是否已经投递，并不保证可靠交付
    if (window.navigator && navigator.sendBeacon && !isQQEnv()&&useXHR===false) {
      if(GS.sett.sm4Config!==undefined&&/^[A-Za-z0-9_-]{1,256}$/.test(GS.sett.sm4Config.identify || GS.sett.sm4Config.identifier)){
        try{
          if(isDefined(window.BonreeRecord)&&window.BonreeRecord.Sm4){
            var sm4=new window.BonreeRecord.Sm4(GS.sett.sm4Config);
          }
          if(isDefined(window.BonreeAgent)&&window.BonreeAgent.Sm4){
            var sm4=new window.BonreeAgent.Sm4(GS.sett.sm4Config);
          }
        }catch(e){
          log("C156");
          var identify=GS.sett.sm4Config.identify || GS.sett.sm4Config.identifier;
          return callback(navigator.sendBeacon(url.replace(`&BR-Encryption-Method=sm4:${identify}`,''), stringify(body)))
        }
        return callback(navigator.sendBeacon(url,sm4.encrypt(stringify(body))))
      }
      return callback(navigator.sendBeacon(url, stringify(body)))
    }
    if(GS.sett.sm4Config!==undefined){
      if(isDefined(window.BonreeRecord)&&window.BonreeRecord.Sm4){
        var sm4=new window.BonreeRecord.Sm4(GS.sett.sm4Config);
        return prePost(url, sm4.encrypt(stringify(body)), callback, force,uid)
      }
      if(isDefined(window.BonreeAgent)&&window.BonreeAgent.Sm4){
        var sm4=new window.BonreeAgent.Sm4(GS.sett.sm4Config);
        return prePost(url, sm4.encrypt(stringify(body)), callback, force,uid)
      }
    }
    return prePost(url, stringify(body), callback, force,uid)

  }

  // WORKER--//数据push服务，推送数据到business层面
  // IDLE--5000 //数据推送周期间隔5s(单位)
  // CAPACITY--50 // 数据上报条数限制
  // RETRY--3 //失败重试三次
  let sst=0;
  let DATA_QUEUE = [];
  let pushConfig={
      WORKER:null,
      IDLE:0,
      CAPACITY:0,//kb
      RETRY:3
  };
  let TOTAL_SIZE=0;
  const sessionCache='br-session-cache';
  pushConfig.changeData=function(data){
      this.WORKER=data;
  };
  function setTotalSize(size){
      TOTAL_SIZE=TOTAL_SIZE+size;
      return TOTAL_SIZE
  }
  function getCycleTime(){
      if(pushConfig.IDLE>0) return
      const cycleTime=Number(GS.sett.cycleTime)||Number(GS.secondSett.cycleTime)||10;
      if(cycleTime&&cycleTime>0&&cycleTime<=60){
          pushConfig.IDLE= cycleTime*1000;
      }else {
          pushConfig.IDLE=10*1000;
      }
  }
  function getMaxSize(){
      if(pushConfig.CAPACITY>0) return
      const maxSize=Number(GS.sett.maxSize)||Number(GS.secondSett.maxSize)||20;
      if(maxSize&&maxSize>0&&maxSize<=60){
          pushConfig.CAPACITY= maxSize*1024;
      }else {
          pushConfig.CAPACITY=20*1024;
      }
  }
  /**
   * @descripe 从DATA_QUEUE中取出最小ent
   * @param {*} data DATA_QUEUE数组
   **/
  function checkoutSessionStart(data){
      var minTime=0;
      if(data.length===0){
          return
      }
      forEach(data,function(unit){
          if(minTime===0){
              minTime=unit.ent;
          }else {
              if(minTime>unit.ent){
                  minTime=unit.ent;
              }
          }
      });
      return minTime
  }
  function pusher(){
      notifierOn(GC.FLUSH_DATA,function(evt){
          getCycleTime();
          //由于安卓注入脚本时机会在非loaded就加载导致没有设置上报定时
          if(GS.sett.osType===1&& !isDefined(pushConfig.WORKER)){
              let w=setInterval(flushData,pushConfig.IDLE);
              pushConfig.changeData(w);
          }
          if(globalData.state>1 && !isDefined(pushConfig.WORKER)){
              let w=setInterval(flushData,pushConfig.IDLE);
              pushConfig.changeData(w);
          } 
          flushData(evt.p);
      });
      /*会话session切换时初始化sst*/
      notifierOn(GC.INIT_SESSION_START,function(evt){
          sst=0;
      });
  }
  function uploadMetric(body, force, callback) {
      const protocol = new Protocol();
      let appInfo = { 
          'ai':GS.sett.appId || GS.secondSett.appId,
          "av":(GS.sett.appVersion||GS.secondSett.appVersion) || 'unknown',
          "an":(GS.sett.appName||GS.secondSett.appName)||'unknown',
          "at":4
      };
      if(isDefined(GS.sett.channelId)){
          appInfo['ci']=GS.sett.channelId;
      }
      protocol.setMonitorTime(now())
          .setConfigTime(GS.sett.initTime)
          .setSessionId(sessionM.getSession().sessionID)
          .setAppInfo(appInfo)
          .setUserInfo(globalData.getUserInfo())
          .setFirstUserInfoIndex();
      if(isDefined(window.BonreeAgent)&&isDefined(window.BonreeAgent.getDeviceInfo)){
          protocol.setDeviceInfo(window.BonreeAgent.getDeviceInfo());
      }else {
          log("C153");
      }
      if(isDefined(window.BonreeRecord)&&isDefined(window.BonreeRecord.getDeviceInfo)){
          protocol.setDeviceInfo(window.BonreeRecord.getDeviceInfo());
      }else {
          log("C153");
      }
      if(isDefined(GS.sett.dataFusionInfo)&&GS.sett.dataFusionInfo=='net'){
          protocol.setDataFusionInfo('net');
      }
      /*sst为0代表会话切换了*/
      if(sst===0){
          sst=checkoutSessionStart(DATA_QUEUE);
          protocol.setSessionStartTime(sst);
      }else {
          protocol.setSessionStartTime(sst);
      }
      //一包数据存在最大会话时长
      let startTime = 0;
      let endTime = 0;
      //循环构造event协议体结构
      forEach(body, function (item) {
          const ent = item.ent;
          if (ent < startTime || startTime === 0) {
              startTime = ent;
          }
          if (ent > endTime || endTime === 0) {
              endTime = ent;
          }
          /*遍历revts中获取endtime*/
          if(isDefined(item.revts)){
              for(let unitEvent of item.revts){
                  if (unitEvent.ent < startTime) {
                      startTime = unitEvent.ent;
                  }
                  if (unitEvent.ent > endTime) {
                      endTime = unitEvent.ent;
                  }
              }
          }
          // setSSTTime(ent)
          // protocol.setSessionStartTime(sessionM.getSession().startTime)
          protocol.pushEventData(item);
      },setSSTTime);
      let usd=usdManager.usdTime&&endTime-usdManager.usdTime||endTime - startTime;
      usd=Math.abs(usd);
      usdManager.changUsdTime(endTime);
      protocol.setSessionDuration(usd);
      const uploadData=protocol.build();
      sendUpload(uploadData, force, callback);
      //设置sst
      function setSSTTime(){
          let sessionData= getCookie(sessionCache);
          var sessionArr=isJSON(sessionData) && JSON.parse(sessionData) || [];
          for(let ele of sessionArr){
              if(isDefined(ele.startTime)&&ele.startTime==0){
                  ele.startTime=startTime;
                  sessionM.setSessionCookie(sessionCache,JSON.stringify(sessionArr));
              }
          }
      }
  }



  /**
   * 数据发送服务
   * @param {*} body 
   * @param {*} force 
   * @param {*} callback 
   * @returns 
   */
  function send(body, force, callback) {
      //无数据需要推送的时候，直接返回
      if (!isDefined(body) || isEmpty(body)) {
          return;
      }
      try {
          //数据直接上报服务器
          uploadMetric(body, force, callback);
          callback && callback(true);
      } catch (err) {
          log(err);
          callback && callback(false);
      }
      return true;
  }
  function prepareCleanTask(datas, force) {
      let cache = [];
      let curSession;
      let retry = 0;
      let totalSize=0;
      // 连续失败超过重试次数，认为服务不通，后续放弃尝试
      // 视将来的需求，有本地持久化的需要可以考虑
      if (retry >= pushConfig.RETRY) {
          return log('C117')
      }
      function checkCache(mandatory, newSession) {
          if (isEmpty(cache)) {
              return
          }
          getMaxSize();
          if (mandatory || totalSize > pushConfig.CAPACITY) {
              send(cache, force, function (success) {
                  if (!success) {
                      retry += 1;
                      if (!force) {
                          delay(function () {
                              const dataSize=size(datas);
                              totalSize=totalSize+dataSize;
                              cache.push(datas);
                          }, pushConfig.IDLE / 10);
                      }
                  } else {
                      if (retry > 0) {
                          retry = 0;
                      }
                  }
              });
              cache = [];
              totalSize=0;
              curSession = mandatory === 1 ? newSession : null;
          }
      }
      forEach(datas, (item) => {
          const sessionInfo = item.data&&item.data.e;
          if (!isDefined(sessionInfo)) {
              totalSize=totalSize+item.size;
              cache.push(item.data);
              return checkCache.call(this)
          }

          const sid = sessionInfo[0];
          const sessionStart = sessionInfo[1];
          const infoData = item.data&&item.data.p.info;
          infoData['userTime'] = Math.max(0, infoData['timestamp'] - sessionStart);
          if (!isDefined(curSession)) {
              curSession = sid;
          }

          if (curSession !== sid) {
              checkCache.call(this, 1, sid);
          }
          totalSize=totalSize+item.size;
          cache.push(item.data);
          checkCache.call(this);
      });

      checkCache.call(this, 2);
  }
  // 推出数据，清空缓存队列
  // @param {*} force为强制推送标识
  function flushData(force){
      if (!isEmpty(DATA_QUEUE)) {
          if(!getUserIdManageClass.useAPI){
              getUserIdManageClass.startCatchDataFun();
          }
          prepareCleanTask(DATA_QUEUE, force);
          DATA_QUEUE = [];
          TOTAL_SIZE=0;
      }
  }

  var spanRecord={};
  class SpanStruct{
      //isChild:标识是否是主span   startTime:为主span的开始时间 deep:记录层次深度 special:标识是否返回特殊object,避免客户不当调用报错
      constructor(name,type,isChild=false,startTime,deep=-1,special=false,identify){
          this.isChild=isChild;
          if(isDefined(startTime)){
              this.startTime=startTime;
          }
          if(isDefined(name)&&isDefined(type)&&typeof name==='string'&&typeof type==='string'&&/^[a-zA-Z0-9:_-\s@./]+$/.test(type)&&type.trim()!==""&&/^[a-zA-Z0-9:_-\s@./]+$/.test(name)&&name.trim()!==""){
              this.spanEvent={
                  n:name.slice(0,256),
                  t:type.slice(0,256),
                  da:[],
                  tag:[],
                  m:[],
                  ic:true,
                  st:isDefined(startTime)?new Date().getTime()*1000-startTime:0
              };
              this.special=special;
          }else {
              this.special=true;
          }
          // 不是子节点且不是特殊类型---定义span开始
          if(!isChild&&!this.special){
              this.spanEvent['timestamp']=new Date().getTime()*1000;
              this.startTime=this.spanEvent['timestamp'];
          }
          // 不是子节点定义标识id，并且是第0层（最外层）
          if(!isChild){
              this.identify=uuid();
              spanRecord[this.identify]=0;
          }else {
              // 是子节点的话，层级加1
              this.identify=identify;
              spanRecord[this.identify]=spanRecord[this.identify]+1;
          }
          this.dataSave=[];
          this.tagSave=[];
          this.metricSave=[];
          this.childSave=[];
          this.hasFinished=false;
          this.deep=deep+1;
          
      }
      startChild(name,type){
          //无效调用返回特殊实例,避免后续调用报错
          if(this.hasFinished){
              return new SpanStruct('name','type',true,this.startTime,this.deep,true,this.identify) 
          }
          if(!(isDefined(name)&&isDefined(type)&&typeof name==='string'&&typeof type==='string'&&/^[a-zA-Z0-9:_-\s@./]+$/.test(type)&&type.trim()!==""&&/^[a-zA-Z0-9:_-\s@./]+$/.test(name)&&name.trim()!=="")){
              return  new SpanStruct('name','type',true,this.startTime,this.deep,true,this.identify)
          }
          if(this.special){
              return  new SpanStruct('name','type',true,this.startTime,this.deep,true,this.identify)
          }
          //最多10层限制
          if(this.deep>=10){
              return new SpanStruct('name','type',true,this.startTime,this.deep,true,this.identify)
          }
          //每层最多50个限制
          if(isDefined(this.childSave)&&this.childSave.length>=50){
              return new SpanStruct('name','type',true,this.startTime,this.deep,true,this.identify)
          }
          //span总数控制200个
          if(isDefined(spanRecord)&&isDefined(spanRecord[this.identify])&&spanRecord[this.identify]>=200){
              return new SpanStruct('name','type',true,this.startTime,this.deep,true,this.identify)
          }
          if(isDefined(this.spanEvent)){
              var childSpan=new SpanStruct(name,type,true,this.startTime,this.deep,false,this.identify);
              if(isDefined(this.spanEvent['sub'])){
                  this.spanEvent['sub'].push(childSpan.spanEvent);
              }else {
                  this.spanEvent['sub']=[childSpan.spanEvent];
              }
              this.childSave.push(childSpan);
              return childSpan
          } 
      }
      setData(key,value){
          if(this.special){
              return
          }
          if(this.hasFinished){
              return
          }
          if(!(isDefined(key)&&isDefined(value)&&typeof key==='string'&&typeof value==='string')){
              return
          }
          if(key.length>200 || !/^[a-zA-Z][a-zA-Z\.\_-]*[a-zA-Z]$|^[a-zA-Z]$/.test(key) || key.trim()===""){
              return
          }
          if(value.trim()===""){
              return
          }
          //64个控制
          if(isDefined(this.spanEvent.da)&&this.spanEvent.da.length>=64){
              return
          }
          if(isDefined(this.spanEvent.da)){
              if(this.spanEvent.da.length>0){
                  if(isDefined(this.dataSave)&&this.dataSave.indexOf(key)>-1){
                     for(let i=0;i<this.spanEvent.da.length;i++){
                          if(isDefined(this.spanEvent.da[i]['k'])&&this.spanEvent.da[i]['k']===key){
                              this.spanEvent.da[i]['k']=key;
                              this.spanEvent.da[i]['v']=value.slice(0,7000);
                          }
                     }
                  }else {
                      this.spanEvent.da.push({k:key,v:value.slice(0,7000)});
                      this.dataSave.push(key);
                  }
              }else {
                  this.spanEvent.da.push({k:key,v:value.slice(0,7000)});
                  this.dataSave.push(key);
              }     
          }    
      }
      removeData(key){
          if(this.special){
              return
          }
          if(this.hasFinished){
              return
          }
          if(!isDefined(key) || typeof key!=='string'){
              return
          }
          if(key.length>200 || !/^[a-zA-Z][a-zA-Z\.\_-]*[a-zA-Z]$|^[a-zA-Z]$/.test(key) || key.trim()===""){
              return
          }
          if(isDefined(this.dataSave)&&this.dataSave.indexOf(key)>-1){
              for(let i=0;i<this.spanEvent.da.length;i++){
                  if(isDefined(this.spanEvent.da[i]['k'])&&this.spanEvent.da[i]['k']===key){
                      this.spanEvent.da.splice(i,1);
                      let index=this.dataSave.indexOf(key);
                      this.dataSave.splice(index,1);
                  }
             }
          }else {
              return
          }    
      }
      setTag(key,value){
          if(this.special){
              return
          }
          if(this.hasFinished){
              return
          }
          if(!(isDefined(key)&&isDefined(value)&&typeof key==='string'&&typeof value==='string')){
              return
          }
          if(key.length>200 || !/^[a-zA-Z][a-zA-Z\.\_-]*[a-zA-Z]$|^[a-zA-Z]$/.test(key) || key.trim()===""){
              return
          }
          if(value.trim()===""){
              return
          }
          //64个控制
          if(isDefined(this.spanEvent.tag)&&this.spanEvent.tag.length>=64){
              return
          }
          if(isDefined(this.spanEvent.tag)){
              if(this.spanEvent.tag.length>0){
                  if(isDefined(this.tagSave)&&this.tagSave.indexOf(key)>-1){
                      for(let i=0;i<this.spanEvent.tag.length;i++){
                           if(isDefined(this.spanEvent.tag[i]['k'])&&this.spanEvent.tag[i]['k']===key){
                               this.spanEvent.tag[i]['k']=key;
                               this.spanEvent.tag[i]['v']=value.slice(0,7000);
                           }
                      }
                  }else {
                      this.spanEvent.tag.push({k:key,v:value.slice(0,7000)});
                      this.tagSave.push(key);
                  }
              }else {
                  this.spanEvent.tag.push({k:key,v:value.slice(0,7000)});
                  this.tagSave.push(key);
              }
          }
      }
      removeTag(key){
          if(this.special){
              return
          }
          if(this.hasFinished){
              return
          }
          if(!isDefined(key) || typeof key!=='string'){
              return
          }
          if(key.length>200 || !/^[a-zA-Z][a-zA-Z\.\_-]*[a-zA-Z]$|^[a-zA-Z]$/.test(key) || key.trim()===""){
              return
          }
          if(isDefined(this.tagSave)&&this.tagSave.indexOf(key)>-1){
              for(let i=0;i<this.spanEvent.tag.length;i++){
                  if(isDefined(this.spanEvent.tag[i]['k'])&&this.spanEvent.tag[i]['k']===key){
                      this.spanEvent.tag.splice(i,1);
                      let index=this.tagSave.indexOf(key);
                      this.tagSave.splice(index,1);
                  }
             }
          }else {
              return
          }    
      }
      setMetric(key,value,unit){
          if(this.special){
              return
          }
          if(this.hasFinished){
              return
          }
          if(!isDefined(key) || !isDefined(value) || typeof value !=='number' || typeof key!=='string'){
              return
          }
          if(key.length>200 || !/^[a-zA-Z][a-zA-Z\.\_-]*[a-zA-Z]$|^[a-zA-Z]$/.test(key) || key.trim()===""){
              return
          }
          //64个控制
          if(isDefined(this.spanEvent.m)&&this.spanEvent.m.length>=64){
              return
          }
          if(isDefined(this.spanEvent.m)){
              if(this.spanEvent.m.length>0){
                  if(isDefined(this.metricSave)&&this.metricSave.indexOf(key)>-1){
                      for(let i=0;i<this.spanEvent.m.length;i++){
                           if(isDefined(this.spanEvent.m[i]['k'])&&this.spanEvent.m[i]['k']===key){
                               this.spanEvent.m[i]['k']=key;
                               this.spanEvent.m[i]['v']=Math.round(value);
                               if(isDefined(unit)&&typeof unit==='string'&&unit.length<=256&&/^[a-zA-Z0-9:_-\s@./]+$/.test(unit)&&unit.trim()!==""){
                                  this.spanEvent.m[i]['u']=unit;
                               }else {
                                  delete this.spanEvent.m[i]['u'];
                               }
                           }
                      }
                  }else {
                      if(isDefined(unit)&&typeof unit==='string'&&unit.length<=256&&/^[a-zA-Z0-9:_-\s@./]+$/.test(unit)&&unit.trim()!==""){
                          this.spanEvent.m.push({k:key,v:Math.round(value),u:unit});
                      }else {
                          this.spanEvent.m.push({k:key,v:Math.round(value)});
                      }
                      this.metricSave.push(key);
                  }
              }else {
                  if(isDefined(unit)&&typeof unit==='string'&&unit.length<=256&&/^[a-zA-Z0-9:_-\s@./]+$/.test(unit)&&unit.trim()!==""){
                      this.spanEvent.m.push({k:key,v:Math.round(value),u:unit});
                  }else {
                      this.spanEvent.m.push({k:key,v:Math.round(value)});
                  }
                  this.metricSave.push(key);
              }
          }

      }
      removeMetric(key){
          if(this.special){
              return
          }
          if(this.hasFinished){
              return
          }
          if(!isDefined(key) || typeof key!=='string'){
              return
          }
          if(key.length>200 || !/^[a-zA-Z][a-zA-Z\.\_-]*[a-zA-Z]$|^[a-zA-Z]$/.test(key) || key.trim()===""){
              return
          }
          if(isDefined(this.metricSave)&&this.metricSave.indexOf(key)>-1){
              for(let i=0;i<this.spanEvent.m.length;i++){
                  if(isDefined(this.spanEvent.m[i]['k'])&&this.spanEvent.m[i]['k']===key){
                      this.spanEvent.m.splice(i,1);
                      let index=this.metricSave.indexOf(key);
                      this.metricSave.splice(index,1);
                  }
             }
          }else {
              return
          }  
      }
      setDuration(duration){
          if(this.special){
              return
          }
          if(this.hasFinished){
              return
          }
          if(!isDefined(duration) || typeof duration!=='number'){
              return
          }
          this.spanEvent['du']=Math.round(duration);
      }
      setStatus(status){
          if(this.special){
              return
          }
          if(this.hasFinished){
              return
          }
          if(!isDefined(status) || typeof status!=='number'){
              return
          }
          if(status===0 || status===1 || status===2){
              this.spanEvent['sta']=status;
          }
          return
      }
      setStatusCode(statusCode){
          if(this.special){
              return
          }
          if(this.hasFinished){
              return
          }
          if(!isDefined(statusCode) || typeof statusCode!=='string'){
              return
          }
          if(statusCode.length>7000 || statusCode.trim()===""){
              return
          }
          this.spanEvent['stac']=statusCode;
      }
      finish(status){
          if(this.special){
              return
          }
          if(this.hasFinished){
              return
          }
          if(isDefined(status) || typeof status==='number'){
              if(status===0 || status===1 || status===2){
                  this.spanEvent['sta']=status;
              }
          }
          this.hasFinished=true;
          //da未设置处理
          if(isDefined(this.spanEvent['da'])&&this.spanEvent['da'].length===0){
              delete this.spanEvent['da'];
          }
          //tag未设置处理
          if(isDefined(this.spanEvent['tag'])&&this.spanEvent['tag'].length===0){
              delete this.spanEvent['tag'];
          }
          //m未设置处理
          if(isDefined(this.spanEvent['m'])&&this.spanEvent['m'].length===0){
              delete this.spanEvent['m'];
          }
          //du未设置处理
          if(!isDefined(this.spanEvent['du'])){
              this.spanEvent['du']=new Date().getTime()*1000-this.startTime-this.spanEvent.st;
          }
          //sta未设置处理
          if(!isDefined(this.spanEvent['sta'])){
              this.spanEvent['sta']=1;
          }
          //必要字段设置检测
          if(!isDefined(this.spanEvent['st']) || !isDefined(this.spanEvent['n']) || !isDefined(this.spanEvent['t'])  || !isDefined(this.spanEvent['ic'])){
              return
          }
          if(isDefined(this.childSave)&&this.childSave.length>0){
              for(let i=0;i<this.childSave.length;i++){
                  this.childSave[i].finish();
              }
          }
          if(!this.isChild){
              if(isDefined(spanRecord)&&isDefined(spanRecord[this.identify])){
                  delete spanRecord[this.identify];
              }
              notifierEmit({t:GC.SPAN_DATA,p:{info:this.spanEvent}});
          }
          
          
      }
  }

  /**
   * @descripe android与鸿蒙桥接数据要求
   **/
  function dataStructHandle(dataStruct,eventType){
      let paraseStruct=JSON.parse(dataStruct);
      paraseStruct["k"]=eventType;
      return paraseStruct
  }
  /**
   * @descripe 移动端对数据桥接的控制
   * @param {*} type |检测的数据类型
   * @return {boolean} 是否采集改数据
   * **/
  function checkMoudle(type){
     if(isDefined(GS.secondSett)&&isDefined(GS.secondSett.mn)){
          if(GS.secondSett.mn.indexOf(type)===-1){
              return false
          }else {
              return true
          }
      }
      return false
  }
  const jsInternalBridge = {
      log: function (logInfo,sett) {
          if(!getDataSize(logInfo,5)){
              return false
          }
          try {
              if (isIOS(sett.osType)) {
                  window.webkit.messageHandlers.brsWKLog.postMessage(logInfo);
                  return;
              }
              if(isHOS(sett.osType)){
                  window.bonreePrivateInterface.call(stringify({log: logInfo}));
                  return;
              }
              window.bonreePrivateInterface.log(logInfo);
          } catch (err) {}
      },
      webviewPerformanceTimingEvent: function (pageDataJson,sett,imd) {
          if(!getDataSize(pageDataJson,5)){
              return false
          }
          if(!checkMoudle('h5')){
              return
          }
          this.log("webviewPerformanceTimingEvent=>" + pageDataJson,sett);
          try {
              if (isIOS(sett.osType)) {
                  window.webkit.messageHandlers.brsWKWebviewPerformanceTimingEvent.postMessage(pageDataJson);
                  return;
              }
              if(isHOS(sett.osType)){
                  window.bonreePrivateInterface.call(stringify({"h5":[dataStructHandle(pageDataJson,"h5")],"imd":imd}));
                  return;
              }
              window.bonreePrivateInterface.webViewEventBus(stringify({"h5":[dataStructHandle(pageDataJson,"h5")],"imd":imd}),sett.webviewID);
          } catch (err) {

          }

      },
      webviewJSErrorEvent: function (errorMessege,sett) {
          if(!getDataSize(errorMessege,5)){
              return false
          }
          if(!checkMoudle('jserror')){
              return
          }
          this.log("webviewJSErrorEvent=>" + errorMessege,sett);
          try {
              if (isIOS(sett.osType)) {
                  window.webkit.messageHandlers.brsWKWebviewJSErrorEvent.postMessage(errorMessege);
                  return;
              }
              if(isHOS(sett.osType)){
                  window.bonreePrivateInterface.call(stringify({"jserror":[dataStructHandle(errorMessege,"jserror")]}));
                  return;
              }
              window.bonreePrivateInterface.webViewEventBus(stringify({"jserror":[dataStructHandle(errorMessege,"jserror")]}),sett.webviewID);
          } catch (error) {

          }

      },
      NetworkEvent: function (ajaxInfo,sett) {
          if(!getDataSize(ajaxInfo,5)){
              return false
          }
          if(!checkMoudle('network')){
              return
          }
          this.log("NetworkEvent=>" + ajaxInfo);
          try {
              if (isIOS(sett.osType)) {
                  window.webkit.messageHandlers.brsWKAjaxPerformanceTimingEvent.postMessage(ajaxInfo);
                  return;
              }
              if(isHOS(sett.osType)){
                  window.bonreePrivateInterface.call(stringify({network:[dataStructHandle(ajaxInfo,"network")]}));
                  return;
              }
              window.bonreePrivateInterface.webViewEventBus(stringify({network:[dataStructHandle(ajaxInfo,"network")],imd:2}),sett.webviewID);
          } catch (error) {

          }

      },
      webviewActionEvent: function (actionInfo,sett) {
          if(!getDataSize(actionInfo,5)){
              return false
          }
          if(!checkMoudle('action')){
              return
          }
          this.log("webviewActionEvent=>" + actionInfo,sett);
          var parseActionInfo =JSON.parse(actionInfo);
          try {
              if (isIOS(sett.osType)) {
                  isDefined(parseActionInfo['v']['ice'])?parseActionInfo['v']['isa']=true:parseActionInfo['v']['isa']=false;
                  window.webkit.messageHandlers.brsWKWebviewActionEvent.postMessage(stringify(parseActionInfo));
                  return;
              }
              if(isHOS(sett.osType)){
                  window.bonreePrivateInterface.call(stringify({action:[dataStructHandle(actionInfo,"action")]}));
                  return;
              }
              window.bonreePrivateInterface.webViewEventBus(stringify({action:[dataStructHandle(actionInfo,"action")]}),sett.webviewID);
          } catch (error) {
             
          }

      },
      webviewPageEvent: function (actionInfo,sett) {
          if(!getDataSize(actionInfo,5)){
              return false
          }
          this.log("webviewPageEvent=>" + actionInfo);
          try {
              if (isIOS(sett.osType)) {
                  window.webkit.messageHandlers.brsWKWebviewPageEvent.postMessage(actionInfo);
                  return;
              }
              if(isHOS(sett.osType)){
                  window.bonreePrivateInterface.call(stringify({view:[dataStructHandle(actionInfo,"view")]}));
                  return;
              }
              window.bonreePrivateInterface.webViewEventBus(stringify({view:[dataStructHandle(actionInfo,"view")]}),sett.webviewID);
          } catch (error) {

          }

      },
      routeChangeData: function (dataInfo,sett) {
          if(!getDataSize(dataInfo,5)){
              return false
          }
          if(!checkMoudle('routechange')){
              return
          }
          this.log("routeChangeData=>" + dataInfo,sett);
          try {   
              if(isIOS(sett.osType)){
                  window.webkit.messageHandlers.brsWKRouteChangeEvent.postMessage(dataInfo);
                  return
              }
              if(isHOS(sett.osType)){
                  window.bonreePrivateInterface.call(stringify({routechange:[dataStructHandle(dataInfo,"routechange")]}));
                  return
              }
              window.bonreePrivateInterface.webViewEventBus(stringify({routechange:[dataStructHandle(dataInfo,"routechange")]}),sett.webviewID);
          } catch (error) {
          }
      },
      consoleEvent: function (consoleData,sett) {
          if(!getDataSize(consoleData,5)){
              return false
          }
          if(!checkMoudle('console')){
              return
          }
          this.log("consoleData=>" ,consoleData,sett);
          try {
              if (isIOS(sett.osType)) {
                  window.webkit.messageHandlers.brsWKConsoleEvent.postMessage(consoleData);
                  return;
              }
              if(isHOS(sett.osType)){
                  window.bonreePrivateInterface.call(stringify({console:[dataStructHandle(consoleData,"console")]}));
                  return;
              }
              window.bonreePrivateInterface.webViewEventBus(stringify({console:[dataStructHandle(consoleData,"console")]}),sett.webviewID);
          } catch (error) {

          }

      },
      spanEvent: function (spanData,sett) {
          if(!getDataSize(spanData,5)){
              return false
          }
          if(!checkMoudle('span')){
              return
          }
          this.log("spanData=>"+spanData,sett);
          try {
              if (isIOS(sett.osType)) {
                  window.webkit.messageHandlers.brsWKSpanEvent.postMessage(spanData);
                  return;
              }
              if(isHOS(sett.osType)){
                  window.bonreePrivateInterface.call(stringify({span:[dataStructHandle(spanData,"span")]}));
                  return;
              }
              window.bonreePrivateInterface.webViewEventBus(stringify({span:[dataStructHandle(spanData,"span")]}),sett.webviewID);
          } catch (error) {

          }

      },
      customLogEvent:function(dataInfo,sett){
          if(!getDataSize(dataInfo,5)){
              return false
          }
          this.log("setCustomLog=>"+dataInfo);
          try {
              if (isIOS(sett.osType)) {
                  window.webkit.messageHandlers.brsWKSetCustomLog.postMessage(dataInfo);
                  return;
              }
              if(isHOS(sett.osType)){
                  window.bonreePrivateInterface.call(stringify({customlog:[dataStructHandle(dataInfo,"customlog")]}));
                  return;
              }
              window.bonreePrivateInterface.webViewEventBus(stringify({customlog:[dataStructHandle(dataInfo,"customlog")]}),sett.webviewID);
          } catch (e) {
          }
      },
      customMetricEvent:function(dataInfo,sett){
          if(!getDataSize(dataInfo,5)){
              return false
          }
          this.log("setCustomMetric=>"+dataInfo);
          try {
              if (isIOS(sett.osType)) {
                  window.webkit.messageHandlers.brsWKSetCustomMetric.postMessage(dataInfo);
                  return;
              }
              if(isHOS(sett.osType)){
                  window.bonreePrivateInterface.call(stringify({custommetric:[dataStructHandle(dataInfo,"custommetric")]}));
                  return;
              }
              window.bonreePrivateInterface.webViewEventBus(stringify({custommetric:[dataStructHandle(dataInfo,"custommetric")]}),sett.webviewID);
          } catch (e) {
          }
      },
      customExceptionEvent:function(dataInfo,sett){
          if(!getDataSize(dataInfo,5)){
              return false
          }
          this.log("setCustomException=>"+dataInfo);
          try {
              if (isIOS(sett.osType)) {
                  window.webkit.messageHandlers.brsWKSetCustomException.postMessage(dataInfo);
                  return;
              }
              if(isHOS(sett.osType)){
                  window.bonreePrivateInterface.call(stringify({crash:[dataStructHandle(dataInfo,"crash")]}));
                  return;
              }
              window.bonreePrivateInterface.webViewEventBus(stringify({crash:[dataStructHandle(dataInfo,"crash")]}),sett.webviewID);
          } catch (e) {
          }
      },
      customSpeedTestEvent:function(dataInfo,sett){
          if(!getDataSize(dataInfo,5)){
              return false
          }
          this.log("speedTest=>"+dataInfo);
          try {
              if (isIOS(sett.osType)) {
                  window.webkit.messageHandlers.brsWKsetCustomSpeedTest.postMessage(dataInfo);
                  return;
              }
              if(isHOS(sett.osType)){
                  window.bonreePrivateInterface.call(stringify({speedtest:[dataStructHandle(dataInfo,"speedtest")]}));
                  return;
              }
              window.bonreePrivateInterface.webViewEventBus(stringify({speedtest:[dataStructHandle(dataInfo,"speedtest")]}),sett.webviewID);
          } catch (e) {
          }
      },
      customEvent:function(dataInfo,sett){
          if(!getDataSize(dataInfo,5)){
              return false
          }
          this.log("setCustomEvent=>"+dataInfo);
          try {
              if (isIOS(sett.osType)) {
                  window.webkit.messageHandlers.brsWKsetCustomEvent.postMessage(dataInfo);
                  return;
              }
              if(isHOS(sett.osType)){
                  window.bonreePrivateInterface.call(stringify({customevent:[dataStructHandle(dataInfo,"customevent")]}));
                  return;
              }
              window.bonreePrivateInterface.webViewEventBus(stringify({customevent:[dataStructHandle(dataInfo,"customevent")]}),sett.webviewID);
          } catch (e) {
          }
      },
      MainDocumentNetworkEvent:function(dataInfo,sett){
          if(!getDataSize(dataInfo,5)){
              return false
          }
          this.log("MainDocumentNetworkEvent=>"+dataInfo);
          try {
              if (isIOS(sett.osType)) {
                  var send=JSON.parse(dataInfo);
                  send.imd=1;
                  window.webkit.messageHandlers.brsWKMainDocumentNetworkEvent.postMessage(stringify(send));
                  return;
              }
              if(isHOS(sett.osType)){
                  window.bonreePrivateInterface.call(stringify({network:[dataStructHandle(dataInfo,"network")],imd:1}));
                  return;
              }
              window.bonreePrivateInterface.webViewEventBus(stringify({network:[dataStructHandle(dataInfo,"network")],imd:1}),sett.webviewID);
          } catch (e) {
              
          }
      },
      ResourceNetworkEvent:function(dataInfo,sett){
          if(!getDataSize(dataInfo,5)){
              return false
          }
          this.log("ResourceNetworkEvent=>"+dataInfo);
          try {
              if (isIOS(sett.osType)) {
                  window.webkit.messageHandlers.brsWKResourceNetworkEvent.postMessage(dataInfo);
                  return;
              }
              if(isHOS(sett.osType)){
                  window.bonreePrivateInterface.call(dataInfo);
                  return;
              }
              window.bonreePrivateInterface.webViewEventBus(dataInfo,sett.webviewID);
          } catch (e) {
          }
      }  
  };

  /*
  Angular框架将window的很多原始值包装了,该方法是获取window原始
  */
  function getZoneJsOriginalValue(browserWindow,name){
      let original=null;
      if (browserWindow.Zone && typeof browserWindow.Zone.__symbol__ === 'function') {
          original = browserWindow[browserWindow.Zone.__symbol__(name)];
        }
      if (!original) {
      original = browserWindow[name];
      }
       return original
  }
  /*
  兼容Angular框架从zone中获取浏览器window原始MutationObserver
  */
  function getMutationObserver(){
      let constructor=null;
      if(window.Zone){
          constructor =getZoneJsOriginalValue(window,'MutationObserver');
      }
      if (window.MutationObserver && constructor === window.MutationObserver) {
          const patchedInstance = new window.MutationObserver(function(){});
          const originalInstance = getZoneJsOriginalValue(patchedInstance, 'originalInstance');
          constructor = originalInstance && originalInstance.constructor;
        }
      if (!constructor) {
          constructor = window.MutationObserver;
        }
        return constructor
      }
  class PageActivityManager{
      constructor(performanceCallback){
          this.mutationRecord = [];
          this.performanceRecord =[];
          this.record=false;
          this.unlocked=true;
          if(window.PerformanceObserver){
              this.PerformanceObserver=new PerformanceObserver((list) => {
                  const entries = list.getEntries();
                  var replayUrl=isDefined(window.$bonreeReplayUrl)?window.$bonreeReplayUrl:null;
                  if (entries.some((entry) => entry.entryType === 'resource')){
                      if(this.record){
                          this.performanceRecord.push(now());
                          if(isDefined(performanceCallback)){
                              performanceCallback(entries.filter(function(entry){return entry.entryType === 'resource' && !isExcludedUrl([GS.sett.uploadAddrHttp,GS.sett.uploadAddrHttps,replayUrl], entry.name.split("?")[0])}));
                          }
                      }
                  }
              });
          }
          var mutationObserverCtor = getMutationObserver();
          if(isDefined(mutationObserverCtor)){
              this.mutationObserver=new mutationObserverCtor((mutationsList) => {
                  /*只需确认有DOM变化即可*/
                  if(this.mutationRecord.lengths>0){
                      this.stopPageActivityObserver(1);
                  }
                  if(this.record){
                      this.mutationRecord.push(now());
                  }
             });
          }
      }
      /*
      开启页面资源与DOM监听
      */
      startPageActivityObserver(){
          if(window.PerformanceObserver){
              this.PerformanceObserver.observe({ entryTypes: ['resource'] });
          }
          this.mutationObserver.observe(window.document, {
              attributes: true,
              attributeOldValue: true,
              characterData: true,
              characterDataOldValue: true,
              childList: true,
              subtree: true
          });
      }
      /*
      开启页面资源与DOM监听记录
      */
      turnOnRecord(){
          this.record=true;
      }
      /*
      关闭页面资源与DOM监听记录
      */
      turnOffRecord(){
          this.record=false;
          this.mutationRecord=[];
          this.performanceRecord=[];
      }
      /*
      停止页面资源与DOM监听
      */
      stopPageActivityObserver(type){
          if(isDefined(type)){
              this.mutationObserver.disconnect();
              return
          }
          if(window.PerformanceObserver){
              this.PerformanceObserver.disconnect();
          }
          if(isDefined(this.mutationObserver)){
              this.mutationObserver.disconnect();
          }   
      }
  }
  /*
  判断采集的记录url是否是业务url
  */
  function isExcludedUrl(list,name){
      if(list.indexOf(name)>-1){
          return true
      }
      return false
  }
  /*
  判断采集的记录中是否在检测时间后有记录
  */
  function checkRecord(arr,checktime){
      if(arr.length===0){
          return  false
      }
      if(arr[arr.length-1]<checktime){
          return false
      }
      for(var i=0;i<=arr.length;i++){
          if(0<=(arr[i]-checktime)/1000){
              return true
          }
      }
      return false
  }
  var pageActivityManager = new PageActivityManager();

  /**
   * 业务数据结构体对象
   * $metric 已转化的协议体数据,业务处理完的数据
   * @param data 原始数据
   * @param type 数据类型
   * @constructor 对象构造器
   */
  class Metric {
      constructor(data, type) {
          this.d_type = type;
          this.data = data || {};
          this.$metric = {};
          const ent = data&&data.info && data.info.timestamp && data.info.timestamp || now();
          this.ent = ent;
          if (globalData.setUserInfoTimeStamp!=0) {
              this.userMapIndex = globalData.lastUserInfoSetMapKey;
          }
      }
  }
  /**
   * 赋值方法
   * @param field
   * @param defaultVal
   * @param prefix
   * @returns {Protocol}
   */
  function extracted(field, val) {
      this.$metric[field] = val;
  }

  /**
   * 获取原始数据Info结构中的指定字段值，重新封装
   * @param {*} field 
   * @param {*} defaultVal 
   * @param {*} alisName 
   * @returns 
   */
  Metric.prototype.info = function (field, defaultVal = '', alisName,unmust=false) {
      const $info = this.data.info;
      if (!isDefined($info)) {
          return this
      }
      let val = $info[field];
      if (!isDefined(val)) {
          val = defaultVal;
      }
      if (isDefined(alisName)) {
          field = alisName;
      }
      if(!(unmust&&val==='')){
          this.$metric[field] = val;
      }
      
      return this
  };
  /**
   * 获取原始数据Metric结构中的指定字段值，重新封装
   * @param {*} field 
   * @param {*} defaultVal 
   * @param {*} alisName 
   * @returns 
   */
  Metric.prototype.metric = function (field, defaultVal = '', alisName) {
      const $metric = this.data.metric;
      if (!isDefined($metric)) {
          return this
      }

      let val = $metric[field];
      if (!isDefined(val)) {
          val = isDefined(defaultVal) ? defaultVal : -1;
      }
      if (isDefined(alisName)) {
          field = alisName;
      }
      extracted.call(this, field, val);
      return this
  };

  /**
   * build方法
   * @returns {*|{}}
   */
  Metric.prototype.build = function (msg) {
      const event = { 'type': this.d_type, 'ent':msg&&msg.ent?msg.ent:this.ent, 'data': {} ,'sin' : [isDefined(this.userMapIndex)?this.userMapIndex:'','','']};
      const unit = this.$metric;
      //有附加值的时候 ，复制给ext属性
      if (isDefined(this.data.ext)) {
          switch (this.d_type) {
              case GC.ACTION:
                  break;
              case GC.NET:
                  break;
              case GC.ERROR:
              case GC.ROUTE:
                  break;
              case GC.PAGE:
              case GC.RESOURCE:
              case GC.WEBVIEWDATA:
              default:
                  unit.ext = this.data.ext;
          }
      }
      event.data = unit;
      return event;
  };
  /**
   * 数据压入业务数据队列
   * @param {*} data Metric数据
   * @param {*} head 是否从头部插入数据
   */
  function pushQueueData(data, head) {
      if (isDefined(data) && isDefined(DATA_QUEUE)) {
          const dataSize=size(data);
          // if (head) {
          //     DATA_QUEUE.unshift(data)
          // }
           //默认数据末尾追加
           DATA_QUEUE.push({data,size:dataSize});
           const totalSize=setTotalSize(dataSize);
           getMaxSize();
          //达到数据阈值时，通知pusher服务，进行数据推送
          if (totalSize > pushConfig.CAPACITY) {
              flushData();
          }
      }
  }

  /**
   * @descripe 2.8.0.0(add)对非关联action的网络数据进行上报控制
   * @param {*} url 网络url
   * @param {*} collectionStrategy 采集策略
   * @return {boolean} yes/no
   **/
  function networkWhiteListHandle(url,collectionStrategy){
      let fullCollection=collectionStrategy.fullCollect || collectionStrategy.fc;
      let whiteList=collectionStrategy.whiteList || collectionStrategy.wl;
      /*09-30909,缺少fc默认全采集*/
      if(!isDefined(fullCollection)){
          return true
      }
      /*全量采集开关为true*/
      if(fullCollection){
          return true
      }else {
          if(isDefined(whiteList)){
              try{
                  var orginUrl=url;
                  var host=undefined || '';
                  if(orginUrl.indexOf("http")===0 || orginUrl.indexOf("file:")===0 || orginUrl.indexOf("ws")===0){
                      if(isDefined(orginUrl.match(/:\/\/\[([^\]]+)\]/))){
                          host=orginUrl.match(/:\/\/\[([^\]]+)\]/)[1];
                      }else {
                          host=orginUrl.match(/:\/\/(.[^/:]+)/)[1];
                      }
                  }else {
                      return false
                  }
              }catch(e){
                  return false
              }
              var hostRule=isDefined(whiteList.hostRule || whiteList.hr)?(whiteList.hostRule || whiteList.hr).slice(0,20):[];
              var pathRule=isDefined(whiteList.pathRule || whiteList.pr)?(whiteList.pathRule || whiteList.pr).slice(0,20):[];
              /*域名匹配*/
              let matchDomain=function(domain,singleConfig){
                  let rule=singleConfig.split("*");
                  /*超过两个星号直接返回no*/
                  if(rule.length>2){
                      return false
                  }
                  /*没有星号*/
                  if(singleConfig.indexOf("*")===-1){
                      if(singleConfig===domain){
                          return true
                      }else {
                          return false
                      }
                  }
                  /*星号中间*/
                  if(rule[0]!==""&&rule[1]!==""){
                      var regEx=new RegExp("("+rule[0]+")"+".+"+"("+rule[1]+")");
                      return regEx.test(domain)
                  }
                  /*星号在前面*/
                  if(rule[0]==""&&rule[1]!==""){
                      if(endWith(domain,rule[1])){
                          return true
                      }else {
                          return false
                      }
                  }
                  /*星号在后面*/
                  if(rule[0]!==""&&rule[1]==""){
                          if(startWith(domain,rule[0])){
                          return true
                      }else {
                          return false
                      }
                  }
                  };
              /*路径匹配*/ 
              let matchPath=function(url,singleConfig){
                      let path=url.split("?")[0];
                      return matchDomain(path,singleConfig)
                  };
              /*遍历hr/pr*/
              let configListHandle=function(configList,type){
                  let handlePolicy=type===1?matchDomain:matchPath;
                  let rule=type===1?host:orginUrl;
                  for(let singleConfig of configList){
                      if(handlePolicy(rule,singleConfig)){
                          return true
                      }
                  }
                  return false 
                  };
              return configListHandle(hostRule,1) || configListHandle(pathRule,2)
              }
          }
      return false
      }
  /**
   * @descripe 获取cs(collectionStrategy)配置
   * @param {*} sett 设置配置参数
   * @returns cs配置/undefined
   **/
  function getcollectionStrategy(sett){
          var collectionStrategy=undefined;
          if(isDefined(sett.collectionStrategy)){
              collectionStrategy=sett.collectionStrategy;
          }else {
                  if(isDefined(sett.mc)&&sett.mc instanceof Array){
                      sett.mc.forEach(function(value){
                          if(value.n==='network'){
                              if(isDefined(value.cs)){
                                  collectionStrategy=value.cs;
                              }
                              return
                          }
                      });
                  }
              }
          return collectionStrategy
      }
  /**
  @param {number} type maskType 
  @param {object} snr  SensitiveNetworkRule
  @param {object} data networkOrginData
  @param {object} sett 配置
  @describe different handle of different maskType
  **/
  function sensitiveTypeHandle(snr,data,sett){
      var maskPolicy=function(){
          var maskKeys=snr.mk || snr.maskKeys;
          var maskType=snr.mt || snr.maskType;
          //aqk handle
          let queryKeys=isDefined(maskKeys.qka || maskKeys.urlKeys)&&(maskKeys.qka || maskKeys.urlKeys);
          if(maskKeys.aqk || maskKeys.allQueryKeys){
              switch(maskType){
                  case 1:
                      data.p.info.url=data.p.info.url.split("?")[0];
                      if(isDefined(sett.reqURLKey)){
                          data.p.info.reqUrlDta=null;
                        }
                      break
                  case 2:
                      data.p.info.url=data.p.info.url.replace(/(\?|&)([^=&]+)=([^&]+)/g, '$1$2=**');
                      if(isDefined(sett.reqURLKey)){
                          data.p.info.reqUrlDta=data.p.info.url.split("?")[1];
                        }
                      break
                  default:
                      return 
              }
          }else {
              if(isDefined(queryKeys)&&queryKeys.length>0){
                  if(data.p.info&&data.p.info.url&&data.p.info.url.indexOf("?")>-1){
                      var queryParams=data.p.info.url.split("?")[1];
                      var keyValues=queryParams.split("&");
                      var urlMaskResult="";
                      for (let i = 0; i < keyValues.length; i++) {
                          let item = keyValues[i].split('=');
                          switch(maskType){
                             case 1:
                              if(includes((maskKeys.qka || maskKeys.urlKeys),item[0])){
                                  continue
                              }
                              urlMaskResult+=keyValues[i]+"&";
                              break
                             case 2:
                              if(includes((maskKeys.qka || maskKeys.urlKeys),item[0])){
                                  urlMaskResult+=keyValues[i].split("=")[0]+"=**"+"&";
                                  continue
                              }
                              urlMaskResult+=keyValues[i]+"&";
                              break
                          }
                          }
                      if(isDefined(sett.reqURLKey)){
                          data.p.info.reqUrlDta=urlMaskResult.slice(0,-1);
                      }
                      if(urlMaskResult.slice(0,-1)!==""){
                          data.p.info.url=data.p.info.url.split("?")[0]+"?"+urlMaskResult.slice(0,-1);
                      }else {
                          data.p.info.url=data.p.info.url.split("?")[0];
                      }
                      
                  }
                  
              }
          }
          //areqh handle
          let requestHeadersKeys=isDefined(maskKeys.reqhka || maskKeys.requestHeadersKeys)?(maskKeys.reqhka || maskKeys.requestHeadersKeys):[];
          requestHeadersKeys=requestHeadersKeys.map(function(value){return value.toLowerCase()});
          if(maskKeys.areqh || maskKeys.allRequestHeaders){
              switch(maskType){
                  //header all delete
                  case 1:
                      data.p.info[GC.REQUEST_HEADER]=undefined;
                      //reqht
                      data.p.info["reqhtData"]={};
                      break
                  //headers all sensitive
                  case 2:
                      if(isDefined(data.p.info[GC.REQUEST_HEADER])){
                          data.p.info[GC.REQUEST_HEADER]=data.p.info[GC.REQUEST_HEADER].replace(/:(.*?)($|\r\n)/g, ":**$2");
                      }
                      //reqht
                      if(isDefined(sett.reqHeaderTraceKey)&&sett.reqHeaderTraceKey.length>0){
                          if(!isEmpty(data.p.info["reqhtData"])){
                          forEach(data.p.info["reqhtData"],function(value,key){
                              data.p.info["reqhtData"][key]="**";
                              });
                          }
                      }
                      break
                  default:
                      return
              }
          }else {
              switch(maskType){
                  //part of headers delete
                  case 1:
                      if(isDefined(data.p.info[GC.REQUEST_HEADER])){
                          if(isDefined(requestHeadersKeys)&&requestHeadersKeys.length>0){
                              for(let key of requestHeadersKeys){
                                  let regex = new RegExp(key+":(.*?)(\r\n|$)","i");
                                  if(regex.test(data.p.info[GC.REQUEST_HEADER])){
                                      data.p.info[GC.REQUEST_HEADER]=data.p.info[GC.REQUEST_HEADER].replace(regex,'');
                                  }
                              }
                          }  
                      }
                      //reqht
                      if(isDefined(sett.reqHeaderTraceKey)&&sett.reqHeaderTraceKey.length>0){
                          if(!isEmpty(data.p.info["reqhtData"])){
                             for(let key in data.p.info["reqhtData"]){
                                  if(includes(requestHeadersKeys,key.toLowerCase())){
                                      delete data.p.info["reqhtData"][key];
                                      continue
                                  }
                             }
                          }
                       }
                      break
                  //part of headers sensitive
                  case 2:
                      if(isDefined(data.p.info[GC.REQUEST_HEADER])){
                          if(isDefined(requestHeadersKeys)&&requestHeadersKeys.length>0){
                              for(let key of requestHeadersKeys){
                                  let regex = new RegExp(key+":(.*?)(\r\n|$)","i");
                                  if(regex.test(data.p.info[GC.REQUEST_HEADER])){
                                      data.p.info[GC.REQUEST_HEADER]=data.p.info[GC.REQUEST_HEADER].replace(regex,function(match,p1){
                                          return match.replace(p1,"**")
                                      });
                                  }
                              }
                          }  
                      }
                      //reqht
                      if(isDefined(sett.reqHeaderTraceKey)&&sett.reqHeaderTraceKey.length>0){
                          if(!isEmpty(data.p.info["reqhtData"])){
                             for(let key in data.p.info["reqhtData"]){
                                  if(includes(requestHeadersKeys,key.toLowerCase())){
                                      data.p.info["reqhtData"][key]="**";
                                      continue
                                  }
                             }
                          }
                       }
                      break
                  default:
                      return
              }
          }
          //aresh handle
          let responseHeaderKeys=isDefined(maskKeys.reshka || maskKeys.responseHeadersKeys)?(maskKeys.reshka || maskKeys.responseHeadersKeys):[];
          responseHeaderKeys=responseHeaderKeys.map(function(val){return val.toLowerCase()});
          if(maskKeys.aresh || maskKeys.allResponseHeaders){
              switch(maskType){
                  //all of response headers delete
                  case 1:
                      if(isDefined(data.p.info.responseHeader)){
                          delete data.p.info.responseHeader;
                      }
                      //resht
                      if(!isEmpty(data.p.info["reshtData"])){
                          delete data.p.info["reshtData"];
                      }
                      //tid
                      if(isDefined(data.p.info.guid)){
                          delete data.p.info.guid;
                      }
                      //xbr
                      if(isDefined(data.p.info.xBrResponse)){
                          delete data.p.info.xBrResponse;
                      }
                      //trsp
                      if(isDefined(data.p.info.traceResponse)){
                          delete data.p.info.traceResponse;
                      }
                      break
                  //all of response headers sensitive
                  case 2:
                      if(isDefined(data.p.info.responseHeader)){
                          data.p.info.responseHeader=data.p.info.responseHeader.replace(/:(.*?)($|\r\n)/g, ":**$2");
                      }
                      //resht
                      if(!isEmpty(data.p.info["reshtData"])){
                          forEach(data.p.info["reshtData"],function(value,key){
                              data.p.info["reshtData"][key]="**";
                          });
                      }
                      //tid
                      if(isDefined(data.p.info.guid)&&data.p.info.guid!==""){
                          data.p.info.guid="**";
                      }
                      //xbr
                      if(isDefined(data.p.info.xBrResponse)&&data.p.info.xBrResponse!=""){
                           data.p.info.xBrResponse="**";
                      }
                      //trsp
                      if(isDefined(data.p.info.traceResponse)&&data.p.info.traceResponse!==""){
                           data.p.info.traceResponse="**";
                      }
                      break
                  default:
                      return
              }
          }else {
              switch(maskType){
                  //part of headers delete
                  case 1:
                      if(isDefined(data.p.info.responseHeader)){
                          for(let key of responseHeaderKeys){
                              let regex = new RegExp(key+":(.*?)(\r\n|$)","i");
                              if(regex.test(data.p.info.responseHeader)){
                                  data.p.info.responseHeader=data.p.info.responseHeader.replace(regex,'');
                              }
                          }
                      }
                      //resht
                      if(!isEmpty(data.p.info["reshtData"])){
                          forEach(data.p.info["reshtData"],function(value,key){
                              if(includes(responseHeaderKeys,key.toLowerCase())){
                                  delete data.p.info["reshtData"][key];
                              }
                          });
                      }
                      //tid
                      if(isDefined(data.p.info.guid)){
                         if(includes(responseHeaderKeys,'br-resp-key')){
                          delete data.p.info.guid;
                         }
                      }
                      //xbr
                      if(isDefined(data.p.info.xBrResponse)){
                           if(includes(responseHeaderKeys,"x-br-response")){
                              delete data.p.info.xBrResponse;
                           }
                      }
                      //trsp
                      if(isDefined(data.p.info.traceResponse)){
                          if(includes(responseHeaderKeys,"traceresponse")){
                              delete data.p.info.traceResponse;
                          }
                      }
                      break
                  case 2:
                      if(isDefined(data.p.info.responseHeader)){
                          for(let key of responseHeaderKeys){
                              let regex = new RegExp(key+":(.*?)(\r\n|$)","i");
                              if(regex.test(data.p.info.responseHeader)){
                                  data.p.info.responseHeader=data.p.info.responseHeader.replace(regex,function(match,p1){
                                      return match.replace(p1,"**")
                                  });
                              }
                          }
                      }
                      //resht
                      if(!isEmpty(data.p.info["reshtData"])){
                          forEach(data.p.info["reshtData"],function(val,key){
                              if(includes(responseHeaderKeys,key.toLowerCase())){
                                  data.p.info["reshtData"][key]="**";
                              }
                          });
                      }
                      //tid
                      if(isDefined(data.p.info.guid)){
                         if(includes(responseHeaderKeys,'br-resp-key')){
                           data.p.info.guid="**";
                         }
                      }
                      //xbr
                      if(isDefined(data.p.info.xBrResponse)){
                           if(includes(responseHeaderKeys,"x-br-response")){
                              data.p.info.xBrResponse="**";
                           }
                      }
                      //trsp
                      if(isDefined(data.p.info.traceResponse)){
                          if(includes(responseHeaderKeys,"traceresponse")){
                              data.p.info.traceResponse="**";
                          }
                      }
                      break
                  default:
                      return
              }
          }
      
      
      };
      maskPolicy();
      }
  /**
  @param {object} data networkOrginData
  @describe SensitiveNetworkRule handle entry,2.4.1(1.7.1) add business
  **/
  function sensitiveRuleHandle(data,sett){
      if(isDefined(sett)&&(isDefined(sett.sensitiveNetworkRule) || isDefined(sett.snr))){
          try{
              var orginUrl=data.p.info.url;
              var host;
              if(orginUrl.indexOf("http")===0 || orginUrl.indexOf("file:")===0 || orginUrl.indexOf("ws")===0){
                  host=orginUrl.match(/:\/\/(.[^/:?]+)/)[1];
              }else {
                  return data
              }
          }catch(e){
              return data
          }
          var sensitiveNetworkRule=sett.sensitiveNetworkRule || sett.snr;
          //单个SensitiveNetworkRuleScope处理
          var singelMatchHandle = function(value){
              if(value.type===1 || value.t===1){
                  if(!isDefined((value.c || value.content))){
                      return false
                  }
                  switch (value.r || value.rule){
                      case 1:
                          if(host.toLowerCase()===(value.c || value.content).toLowerCase()){
                              return true
                          }
                          break
                      case 2:
                          if(host.toLowerCase().indexOf((value.c || value.content).toLowerCase())>-1){
                              return true
                          }
                          break
                      case 3:
                          if(startWith(host.toLowerCase(),(value.c || value.content).toLowerCase())){
                              return true
                          }
                          break
                      case 4:
                          if(endWith(host.toLowerCase(),(value.c || value.content).toLowerCase())){
                              return true
                          }
                      default:
                          return false
                  }
              }
              if(value.type===2 || value.t===2){
                  switch (value.r || value.rule){
                      case 1:
                          if(orginUrl===(value.c || value.content)){
                              return true
                          }
                          break
                      case 2:
                          if(orginUrl.indexOf((value.c || value.content))>-1){
                              return true
                          }
                          break
                      case 3:
                          if(startWith(orginUrl,(value.c || value.content))){
                              return true
                          }
                          break
                      case 4:
                          if(endWith(orginUrl,(value.c || value.content))){
                              return true
                          }
                      default:
                          return false

                  }
              }
              return false
              };
          //scopes match
          var matchRules=function(scopes,type){
                  switch(type){
                      case 1:
                          for(let scope of scopes){
                              if(singelMatchHandle(scope)){
                                  return true
                              }
                          }
                          return false
                      case 2:
                          for(let scope of scopes){
                              if(!singelMatchHandle(scope)){
                                  return false
                              }
                          }
                          return true
                      default:
                          return false     
                  }
          };
          for(let item of sensitiveNetworkRule){
              //或方式匹配
              if(item.t===1 || item.type===1){
                  if(matchRules((item.sa || item.scopes),1)){
                      sensitiveTypeHandle(item,data,sett);
                  }
                  continue
              }
              //与方式匹配
              if(item.t===2 || item.type===2){
                  if(matchRules((item.sa || item.scopes),2)){
                      sensitiveTypeHandle(item,data,sett);
                  }
                  continue   
              }
          }
      }
      return data
  }
  /**
  @param {object} data networkOrginData
  @describe compute sslt/rti/dti/dt/ct指标
  **/
  function dataFactory(data) {
      let domianTime = 0; // dns解析时间
      let connetcTime = 0; // tcp建立连接时间
      let sslt = 0;
      let rt=0; // 请求时间，计算规则（responseStart-requestStart）
      let rti = 0;
      let dti = 0;
      let { domainLookupStart, domainLookupEnd, connectStart, connectEnd, responseStart, responseEnd, secureConnectionStart, fetchStart,requestStart } = data.p.metric;
      if (isDefined(domainLookupStart) && isDefined(domainLookupEnd)) {
          if (domainLookupStart > 0) {
              let _dt=domainLookupEnd - domainLookupStart||-1;
              domianTime = _dt > 0 ? _dt : 0;
          }
      }
      if (isDefined(connectStart) && isDefined(connectEnd)) {
          if (connectStart > 0) {
              let _ct=connectEnd - connectStart||-1;
              connetcTime = _ct > 0 ? _ct : 0;
          }
      }
      if (isDefined(connectEnd) && isDefined(secureConnectionStart)) {
          if (secureConnectionStart > 0) {
              let _sslt=connectEnd - secureConnectionStart||-1;
              sslt = _sslt > 0 ? _sslt : 0;
          }
      }
      if (isDefined(responseStart) && responseStart > 0) {
          if(isDefined(requestStart) && requestStart>0){
              let _rti=responseStart-requestStart||-1;
              rti= _rti>=0 ? _rti : 999;
          }
          if (isDefined(connectEnd)&&connectEnd>0) {
              let _rt=requestStart - connectEnd||-1;
              rt = _rt >= 0 ? _rt : 999;
          }
          if (isDefined(responseEnd)) {
              let _dti=responseEnd - responseStart||-1;
              dti = _dti >= 0 ? _dti : 999;
          }
      } else {
          //意味着缓存数据 缓存数据的拉取不走网络，但是 responseEnd ,fetchStart 属性会有相对偏移量更新
          if (isDefined(fetchStart)&&fetchStart>0) {
              let _dti=responseEnd - fetchStart||-1;
              dti = _dti >= 0 ? _dti : 999;
          }
      }
      var metric=isDefined(data.p.metric)?data.p.metric:{};
      metric.domianTime=domianTime;
      metric.connetcTime=connetcTime;
      metric.sslt=sslt;
      metric.rti=rti;
      metric.dti=dti;
      metric.rt=rt;
  }
  /**
  @param {object} data networkOrginData
  @describe 处理请求体匹配/请求头匹配/url匹配等业务
  **/
  function specialCase(data,sett) {
      //根据键值数据取值请求体中的参数
      if (isDefined(sett.reqBodyKey)) {
          let requestBody = '';
          if (isJSON(data.p.info.requestBody)) {
              try {
                  const jsonObj = (new Function("", "return " + data.p.info.requestBody))();
                  forEach(sett.reqBodyKey, function (item, index) {
                      if (isDefined(jsonObj[item])) {
                          requestBody += `${item}=${escape(jsonObj[item])}&`;
                      }
                  });
                  data.p.info[GC.NET_CBBQ] = requestBody.slice(0, -1);
              } catch (err) {
                  // alert(1)
              }
          } else if (isString(data.p.info.requestBody)) {
              try {
                  const arrayParams = data.p.info.requestBody.split('&');
                  forEach(arrayParams, function (param) {
                      forEach(sett.reqBodyKey, function (item, index) {
                          let key = item + '=';
                          if (item && param.indexOf(key) !== -1 ) {
                              requestBody += param.split("=")[0] +"="+escape(param.split("=")[1]) +"&";
                          }
                      });
                  });
                  data.p.info[GC.NET_CBBQ] = requestBody.slice(0, -1);
              } catch (error) {
                  // alert(2)
              }
          }
      }
      if (isDefined(sett.reqURLKey) && isString(data.p.info.reqUrlDta)) {
          try {
              let requestUrl = '';
              const arrayParams = data.p.info.reqUrlDta.split('&');
              forEach(arrayParams, function (param) {
                  forEach(sett.reqURLKey, function (item, index) {
                      if (item && param.split('=')[0]===item) {
                          requestUrl += param.split("=")[0] +"="+escape(param.split("=")[1]) +"&";
                      }
                  });
              });
              data.p.info[GC.NET_CBQ] = requestUrl.slice(0, -1);
          } catch (error) {
              // alert(3)
          }

      }else {
          delete data.p.info[GC.NET_CBQ];
      }
      //构造callbackTime指标数据
      if (isDefined(data.p.metric) && isDefined(data.p.metric[GC.CALLBACK_END]) && isDefined(data.p.metric[GC.CALLBACK_START])) {
          data.p.metric[GC.CALLBACK_TIME] = data.p.metric[GC.CALLBACK_END] - data.p.metric[GC.CALLBACK_START];
          data.p.metric[GC.CALLBACK_TIME] = data.p.metric[GC.CALLBACK_TIME] > 0 && data.p.metric[GC.CALLBACK_TIME] * 1000 || 0;
      }
      if (isDefined(sett.reqHeaderKey) && isDefined(data.p.info) && isDefined(data.p.info[GC.REQUEST_HEADER])) {
          try {
              let requsetHeaderKey = '';
              let headArr = data.p.info[GC.REQUEST_HEADER].split('\r\n');
              forEach(headArr, function (dataItem) {
                  forEach(sett.reqHeaderKey, function (item) {
                      if (isDefined(item) && item!=""&&dataItem.split(':')[0].toLowerCase()===item.toLowerCase()) {
                          requsetHeaderKey += dataItem.split(":")[0]+"="+escape(dataItem.split(":")[1])+'&';
                      }
                  });
              });
              data.p.info[GC.NET_CBHQ] = requsetHeaderKey.slice(0, -1);
          } catch (error) {
              // alert(4)
          }
      }
      return data
  }
  /**
  @param {object} data networkOrginData
  @describe 对非必要字段进行处理
  **/
  function fileHandle(data){
      let resultData=data.data;
      if(isDefined(resultData.tid)&&resultData.tid===""){
          delete resultData.tid;
      }
      if(isDefined(resultData.xbr)&&resultData.xbr===""){
          delete resultData.xbr;
      }
      if(isDefined(resultData.trsp)&&resultData.trsp===""){
          delete resultData.trsp;
      }
      if(isDefined(resultData.tpar)&&resultData.tpar===""){
          delete resultData.tpar;
      }
      if(isDefined(resultData.cbhq)&&resultData.cbhq===""){
          delete resultData.cbhq;
      }
      if(isDefined(resultData.cbbq)&&resultData.cbbq===""){
          delete resultData.cbbq;
      }
      if(isDefined(resultData.cbq)&&resultData.cbq===""){
          delete resultData.cbq;
      }
      if(isDefined(resultData.ti)&&resultData.ti===""){
          delete resultData.ti;
      }
      if(isDefined(resultData.ec)&&200<=resultData.ec&&resultData.ec<400){
          if(isDefined(resultData.ep)){
              delete resultData.ep;
          }
          if(isDefined(resultData.eop)){
              delete resultData.eop;
          }
      }
      if(isDefined(resultData.ec)&&resultData.ec>400&&resultData.ec<=602){
          if(isDefined(resultData.eop)){
              resultData.eop=4;
          }
      }
      if(isDefined(resultData.cbhq)){
          resultData.cbhq=resultData.cbhq.replace("/","%2F");
      }
      //file协议转换200
      if(isDefined(resultData.ec)&&resultData.ec===602&&isDefined(resultData.ru)&&resultData.ru.indexOf("file:")===0){
          resultData.ec=200;
          delete resultData.eop;
          delete resultData.ep;
          delete resultData.em;
      }
      return data
  }
  /**
  @param {object} data networkOrginData
  @describe 对reqht/resht业务处理
  **/
  function headerData(data,sett){
      if(isDefined(sett.reqHeaderTraceKey)&&sett.reqHeaderTraceKey.length>0){
          let reqht={};
          if(isDefined(data.p.info["reqhtData"]&&Object.getOwnPropertyNames(data.p.info["reqhtData"]).length<=64)){
              reqht=data.p.info["reqhtData"];
          }else {
              Object.getOwnPropertyNames(data.p.info["reqhtData"]).slice(0,64).forEach(function(key){
                  reqht[key]=data.p.info["reqhtData"][key];
              });
          }
          if(!isEmpty(reqht)){
              data.p.info['reqht']=reqht;
          }
      }
      if(isDefined(sett.respHeaderTraceKey)&&sett.respHeaderTraceKey.length>0){
          let resht={};
          let b=0;
          for (let i = 0, j = sett.respHeaderTraceKey.length-1;i<=j;i++) {
              if(b<64 &&isDefined(data.p.info["reshtData"]) && isDefined(data.p.info["reshtData"][sett.respHeaderTraceKey[i]])){
                  b+=1;
                  resht[sett.respHeaderTraceKey[i]]=data.p.info['reshtData'][sett.respHeaderTraceKey[i]];
              }
          }
          if(!isEmpty(resht)){
              data.p.info['resht']=resht;
          }
      }
  }
  /**
  @param {object} data networkOrginData
  @describe 对network数据组包序列化
  **/
  function requestService(netData,sett,skipcollectionStrategy=false) {
      /*只对非操作关联网络数据白名单处理*/
      /*获取collection strategy*/
      let data={};
      if(netData){
          // 由于端上嵌入时，会有两套配置对同一个数据生效，原数据经过第一个配置后，数据发生改变，导致再走第二套配置时，本该有的数据被处理
          data=JSON.parse(JSON.stringify(netData));
      }else {
          return
      }
      var collectionStrategy=getcollectionStrategy(sett);
      if(!skipcollectionStrategy&&isDefined(collectionStrategy)){
          if(!networkWhiteListHandle(data.p.info.url || '',collectionStrategy)){
              return null
          }
      }
      try {
          //过滤replay请求
          if(isDefined(window.$bonreeReplayUrl)&&data.p.info.url.indexOf(window.$bonreeReplayUrl)>-1){
              return null
          } 
      } catch (error) {
          
      }

      if(isDefined(data.p.metric)){
          // 构造数据
          dataFactory.call(this, data);
      }
      // 构造数据
      // 经过问题排查，发现有些数据没有metric，胡这里没有做判断
      if(isDefined(data.p.metric)){
          dataFactory.call(this, data);
      }
      if(isDefined(sett.sensitiveNetworkRule || sett.snr)){
          sensitiveRuleHandle.call(this,data,sett);
      }
      specialCase.call(this, data,sett);
      headerData.call(this,data,sett);
      // 判断是否上报rh，rhe
      var requestInfo=data.p.info;
      var hcs=sett.hcs;
      if(isDefined(hcs)&&(isDefined(requestInfo.requestHeader)||isDefined(requestInfo.responseHeader))){
        if(hcs===0){
          // 不上传
          delete data.p.info['requestHeader'];
          delete data.p.info['responseHeader'];
        }else if((hcs===1&&requestInfo.status<400)||(hcs===1&&requestInfo.code < 400)){
          // 仅传错误
          delete data.p.info['requestHeader'];
          delete data.p.info['responseHeader'];
        }
      }
      let pt = data && data.p.info.url && data.p.info.url.indexOf('https') > -1 && 2 || 1;
      let ret =  getMineTypeByHeader(data.p.info[GC.RESPONSE_HEADER])|| getMineTypeByHeader(data.p.info[GC.REQUEST_HEADER]) || getMineTypeByUrl(data.p.info[GC.URL]) || 'text/html';
      const baseData = new Metric(data.p, GC.NET);
      //provide to BrLog
      if(isDefined(baseData.data.info[GC.NET_EC])&&baseData.data.info[GC.NET_EC]>400 || !isDefined(baseData.data.info[GC.NET_EC])){
          isDefined(window.BRLog)&&window.BRLog.__sendNetInfo(baseData.data.info);
      }
      baseData.info("id")
          .info(GC.URL, '', 'ru')
          .info(GC.NET_METHOD, '', 'm')
          .info(GC.NET_IP, '', 'ti')
          .info(GC.NET_PORT, 0, 'tp')
          .info(GC.REQUEST_HEADER, '', 'rh',true)
          .info(GC.RESPONSE_HEADER, '', 'rhe',true)
          .info(GC.NET_TID, '', 'tid')
          .info(GC.NET_XBR,'','xbr')
          .info(GC.NET_TRACE,'','trsp')
          .info('reqht','','reqht',true)
          .info('resht','','resht',true)
          .info(GC.E_TYPE, 'http', 'ep',true)
          .info(GC.NET_EOP,'', 'eop',true)
          .info(GC.NET_TYPE, 3, 'art')
          .info(GC.PAGE_ID, '', 'pvid')
          .info(GC.CUSTOM_IC, false, 'ic')
          .info(GC.NET_CBBQ, '', 'cbbq')
          .info(GC.NET_CBHQ, '', 'cbhq')
          .info(GC.NET_CBQ, '', 'cbq')
          .info('ret',ret,'ret')
          .metric('domianTime', 0, 'dt')
          .metric('connetcTime', 0, 'ct')
          .metric('sslt', 0, 'sslt')
          .metric('rt', 0, 'rt')
          .metric('rti', 0, 'rti')
          .metric('dti', 0, 'dti')
          .metric(GC.DECODED_BODY_SIZE, 0, 'ds')
          .metric(GC.UPLOAD_BODY_SIZE, 0, 'rds')
          .metric(GC.NET_PT, pt, 'pt');
      if(data.p && data.p.info['ai']){
          baseData.info('ai', '', 'ai');
      }
      if (data.p && data.p.info[GC.NET_EC] == 200 || data.p&&data.p[GC.STATUS]== 200) {
          baseData.info(GC.NET_EOP, 0, 'eop');
      }
      if(data.p&&isDefined(data.p.info[GC.NET_EC])){
          baseData.info(GC.NET_EC, 200, 'ec');
      }
      if(data.p&&isDefined(data.p.info[GC.STATUS])){
          baseData.info(GC.STATUS,200,'ec');
      }
      if(data.p&&data.p.info[GC.E_TYPE]==="XHR"){
          baseData.info(GC.MESSAGE, '', 'em',true);
      }
      if(data.p&&data.p.info[GC.E_TYPE]==="FETCH"){
          baseData.info(GC.STATUS_TEXT,'','em',true);
      }
      return fileHandle(baseData.build());

  }
  /**
  @param {object} data networkOrginData
  @describe 对H5的主文档和资源转化network
  **/
  function WebviewPerformanceToNet(data){
      const baseData = new Metric(data, GC.NET);
      let ret = getMineTypeByUrl(data[GC.URL]) || 'text/html';
      baseData.info("id")
          .info('ru')
          .info('m')
          .info('ti')
          .info('tp')
          .info('art')
          .info('pvid','','pvid')
          .info('ic')
          .info('ret',ret,'ret')
          .info('dt')
          .info('ct')
          .info('sslt')
          .info('rt')
          .info('rti')
          .info('dti')
          .info('ds', 0, 'ds')
          .info('rds', 0, 'rds')
          .info('pt')
          .info('ec',200,'ec');
          return fileHandle(baseData.build());
  }

  /**
   * @descripe 对字段的长度与有效校验
   **/
  const filterData = function (filed, value, func, lengthNum, isNumber,isNullValue) {
      if (filed === undefined) {
          return false;
      }
      if (value === undefined || value === null || value === '') {
          jsInternalBridge.log(func + " Parameter has a value or key [" + filed + "] that does not exist!");
          return true;
      }
      if (lengthNum !== null && value.length > lengthNum) {
          jsInternalBridge.log(func + " Parameter has a value or key [" + filed + "] that the value length exceeds " + value.length + "!");
          return true;
      }
      if (isNumber && isNaN(value)) {
          jsInternalBridge.log(func + " Parameter has a value or key [" + filed + "] value is not a valid number!");
          return true;
      }
      return false;
  };
  const MAX_LENGTH_1 = 2083;
  const MAX_LENGTH_2 = 256;
  /**
   * @descripe 对自定义事件info字段的长度与有效校验
   **/
  const filterInfo = function(info){
      var result={};
      if(info!==undefined&&Object.prototype.toString.call(info)==='[object Object]'){
          if(Object.getOwnPropertyNames(info).length>64){
              var infoKeys=Object.getOwnPropertyNames(info).slice(0,64);
              for(let val in infoKeys){
                  if((typeof infoKeys[val] !=="string" || infoKeys[val].length>256) || infoKeys[val]===""){
                      continue
                  }
                  result[infoKeys[val]]=info[infoKeys[val]];
              }
          }else {
              for(let key in info){
                  if((typeof key !=="string" || key.length>256) || key===""){
                      continue
                  }
                  result[key]=info[key];
              }
          }
          if(Object.getOwnPropertyNames(result).length===0){
              return undefined
          }
          return result
      }
      return undefined
  };
  let timeStamp = {};
  let identification = {};
  let correlationId = {};
  let timeStampEvent = {};
  let CustomViewExistQueue = [];
  let CustomEventExistQueue = [];
  /**
   * @descripe 两次注入时对数据进行分流上报处理
   * @param {*} event baseData
   * @param {Function} callback 桥接的方法
   **/
  function dataDevide(event,callback){
      /*后置配置*/
      if(isDefined(GS.secondSett)&&!isEmpty(GS.secondSett)&&!isEmpty(event)){
          /*桥接移动端脱敏url(jserror)*/
          if(isDefined(event.data.url)){
              event.data.url=sensitiveRuleHandle({p:{info:{url:event.data.url}}},GS.secondSett).p.info.url;
          }
          if(isDefined(GS.secondSett.osType)&&GS.secondSett.osType!==GC.BROWSER){
              callback.call(jsInternalBridge,stringify({ent:event.ent,v:event.data}),GS.secondSett);
          }else {
              pushQueueData(event);
          }
      }
      /*前置配置*/
      if(isDefined(GS.sett)&&!isEmpty(GS.sett)&&!isEmpty(event)){
          if(isDefined(GS.sett.osType)&&GS.sett.osType!==GC.BROWSER){
              callback.call(jsInternalBridge,stringify({ent:event.ent,v:event.data}),GS.sett);
          }else {
              pushQueueData(event);
          }
      }
  }
  const jsBridge = {
      setCustomSpeedTest:function(ip,infoArr){
          if(arguments.length<1||arguments.length>2){
              return 
          }
          if(ip&&ip.length>256){
              return 
          }
          if(Array.isArray(infoArr)&&infoArr.length>0&&infoArr.length<=1000){
              let info={};
              if(!isDefined(ip) || ip===""){
                  return
              }
              info.oip=ip;
              info.sti=infoArr;
              const eventData = new Metric({info}, "speedtest");
              eventData.info('oip').info('sti');
              dataDevide(eventData.build(),jsInternalBridge.customSpeedTestEvent);
          }else {
              log('C156');
          }

      },
      setExtraInfo: function (kv) {
          // 设置用户附加属性
          jsInternalBridge.log("setExtraInfo=>" + kv);
          let kvMap = kv && set_64_keys(kv, 64) || kv;
          try {
              setExtraInfo(kvMap);
              if (isIOS(GS.sett.osType) || isIOS(GS.secondSett.osType)) {
                  window.webkit.messageHandlers.brsWKSetExtraInfo.postMessage(stringify(kvMap));
                  return;
              }
              if(isHOS(GS.sett.osType) || isHOS(GS.secondSett.osType)){
                  window.bonreePrivateInterface.call(stringify({setExtraInfo: kvMap}));
                  return;
              }
              window.bonreePrivateInterface.setExtraInfo(stringify(kvMap));
          } catch (e) {
          }
      },
      setUserID: function (userId) {
          // 设置用户id
          jsInternalBridge.log("setUserID=>" + userId);
          if (filterData('userId', userId, 'setUserID', MAX_LENGTH_2, false)) {
              return;
          }
          if (!/^[\u4E00-\u9FFFa-zA-Z0-9:_\-@.\s/]+$/.test(userId)) {
              return
          }
          try {
              setUserID(userId);
              if (isIOS(GS.sett.osType) || isIOS(GS.secondSett.osType)) {
                  window.webkit.messageHandlers.brsWKSetUserId.postMessage(userId);
                  return;
              }
              if(isHOS(GS.sett.osType) || isHOS(GS.secondSett.osType)){
                  window.bonreePrivateInterface.call(stringify({setUserID: userId}));
                  return;
              }
              window.bonreePrivateInterface.setUserID(userId);
          } catch (e) {
          }
      },
      setCustomEventWithLabel: function (eventId, eventName,eventLabel, eventParam,info) {
          // 自定义事件 ActionEvent
          if (arguments.length < 1 || arguments.length > 5) {
              return
          }
          if (filterData('eventId', eventId, 'setCustomEvent', MAX_LENGTH_2, false)) {
              return;
          }
          if(isDefined(info)&&JSON.stringify(info).length>7000){
              return
          }
          let onEventDic = {};
          let eventNameNew = set_length(eventName, MAX_LENGTH_2);
          let eventParamNew = set_length(eventParam, 7000);
          onEventDic.eventId = isDefined(eventId) ? eventId : '';
          onEventDic.eventName = eventNameNew;
          onEventDic.eventParam = eventParamNew;
          onEventDic.eventLabel = set_length(eventLabel, 256);
          onEventDic.info = filterInfo(info);
          const eventData = new Metric({ info: onEventDic }, GC.CUSTOM_EVENT);
          eventData.info('eventId', '', 'i')
              .info('t', 0)
              .info('d', 0);
          if(onEventDic.eventName!==undefined&&onEventDic.eventName!==""&&onEventDic.eventName!==null){
              eventData.info('eventName', '', 'n');
          }
          if(onEventDic.eventLabel!==undefined&&onEventDic.eventLabel!=="unuse"&&onEventDic.eventLabel!==""&&onEventDic.eventLabel!==null){
              eventData.info('eventLabel', '', 'l');
          }
          if(onEventDic.eventParam!==undefined&&onEventDic.eventParam!==""&&onEventDic.eventParam!==null){
              eventData.info('eventParam', '', 'p');
          }
          if(onEventDic.info!==undefined&&onEventDic.info instanceof Object){
              eventData.info("info",'','info');
          }
          dataDevide(eventData.build(),jsInternalBridge.customEvent);
      },
      setCustomEvent: function (eventId, eventName, eventParam,info) {
          this.setCustomEventWithLabel(eventId, eventName,'unuse', eventParam,info);
      },
      setCustomLog: function (logInfo, logParam) {
          // 自定义日志
          if (arguments.length < 1 || arguments.length > 2) {
              jsInternalBridge.log("setcustomlog custom log parameter number error");
              return
          }
          if (filterData('logInfo', logInfo, 'setCustomLog', null, false)) {
              return;
          }
          let logDic = {};
          let logInfoNew = isDefined(logInfo) && set_length(logInfo, 10000) || '';
          let logParamNew = isDefined(logParam)?set_length(logParam, 10000):logParam;
          logDic.logInfo = logInfoNew;
          logDic.logParam = logParamNew;
          const eventData = new Metric({ info: logDic }, GC.CUSTOM_LOG);
          eventData.info('logInfo', '', 'i');
          if(logDic.logParam!==undefined){
              eventData.info('logParam', '', 'p');
          }       
          dataDevide(eventData.build(),jsInternalBridge.customLogEvent);
          return;
      },
      setCustomMetric: function (metricName, metricValue, metricParam) {
          // 自定义指标
          if (arguments.length < 1 || arguments.length > 3) {
              jsInternalBridge.log("setCustomMetric自定义指标参数个数错误");
              return
          }
          if (filterData('metricName', metricName, 'setCustomMetric', MAX_LENGTH_2, false)) {
              return;
          }
          if (filterData('metricValue', metricValue, 'setCustomMetric', null, false)) {
              return;
          }
          let metricDic = {};
          metricDic.metricName = isDefined(metricName) ? metricName : '';
          metricDic.metricValue = isDefined(metricValue) ? Math.round(metricValue) : '';
          if(isDefined(metricParam)){
              metricDic.metricParam = metricParam.length>10000?metricParam.slice(0,10000):metricParam;
          }
          const eventData = new Metric({ info: metricDic }, GC.CUSTOM_METRIC);
          eventData.info('metricName', '', 'n')
                   .info('metricValue', 0, 'v');
          if(metricParam!==undefined){
          eventData.info('metricParam', '', 'p');
          } 
          dataDevide(eventData.build(),jsInternalBridge.customMetricEvent);
          return;
      },
      setCustomException: function (exceptionType, causedBy, errorDump) {
          // 自定义异常
          if (arguments.length < 1 || arguments.length > 3) {
              jsInternalBridge.log("onEvent自定义事件参数个数错误");
              return
          }
          if (filterData('exceptionType', exceptionType, 'setCustomException', MAX_LENGTH_2, false)) {
              return;
          }
          let exctptionDic = {};
          let causedByNew = isDefined(causedBy) && set_length(causedBy, 512) || '';
          let errorDumpNew = isDefined(errorDump) && set_length(errorDump, 10000) || '';
          exctptionDic.exceptionType = isDefined(exceptionType) ? exceptionType : '';
          exctptionDic.causedBy = causedByNew;
          exctptionDic.errorDump = errorDumpNew;
          const eventData = new Metric({ info: exctptionDic }, GC.CRASH);
          eventData.info('causedBy', '', 'cab')
              .info('exceptionType', '', 't')
              .info('errorDump', '', 'p')
              .info('ic', true)
              .info('id',uuid());
          dataDevide(eventData.build(),jsInternalBridge.customExceptionEvent);
          return;
      },
      setCustomPageStart: function (pageName, param) {
          if (arguments.length < 1 || arguments.length > 2) {
              return
          }
          if (filterData('pageName', pageName, 'setCustomPageStart', MAX_LENGTH_2, false)) {
              return;
          }
          if(includes(CustomViewExistQueue,pageName)){
              return
          }
          CustomViewExistQueue.push(pageName);
          /*自定义视图开始记录标识*/
          timeStamp[pageName]=dateNow();
          identification[pageName] = buildViewID();
          if (arguments[0]) {
              let paramNew = set_length(param, MAX_LENGTH_2);
              let onPageStartDic = {
                  "pageName": pageName,
                  "param": paramNew,
              };
              const pageData = new Metric({ info: onPageStartDic }, GC.VIEW);
              pageData.info('pageName', '', 'n')
                  .info('ci', identification[pageName])
                  .info('lt', 0)
                  .info('m', 1)
                  .info('t', 1)
                  .info('ic', true);
              if(param!==undefined){
                  pageData.info('param',"",'p');
              }
              dataDevide(pageData.build(),jsInternalBridge.webviewPageEvent);
          }
      },
      setCustomPageEnd: function (pageName, param) {
          if (arguments.length < 1 || arguments.length > 2) {
              return
          }
          if (filterData('pageName', pageName, 'setCustomPageEnd', MAX_LENGTH_2, false)) {
              return;
          }
          if(!includes(CustomViewExistQueue,pageName)){
              return
          }
          let d = 0;
          /*防止代码重复调用同一视图结束*/
          if (isDefined(dateNow) && timeStamp&&isDefined(timeStamp[pageName])) {
              d = dateNow() - timeStamp[pageName];
              d = d * 1000;
          }else {
              return
          }
          if (arguments[0]) {
              let paramNew = set_length(param, MAX_LENGTH_2);
              let onPageEndDic = {
                  "pageName": pageName,
                  "param": paramNew,
              };
              CustomViewExistQueue=filter(CustomViewExistQueue,function(item){return item !==pageName});
              delete timeStamp[pageName];
              const pageEndData = new Metric({ info: onPageEndDic }, GC.VIEW);
              pageEndData.info('pageName', '', 'n')
                  .info('ci', identification[pageName])
                  .info('st', d)
                  .info('lt', 0)
                  .info('m', 2)
                  .info('t', 1)
                  .info('ic', true);
              if(param!==undefined){
                  pageEndData.info('param',"",'p');
              }
              dataDevide(pageEndData.build(),jsInternalBridge.webviewPageEvent);
              delete identification[pageName];
          }
      },
      setCustomH5performanceData: function (dataInfoStr) {
          let dataInfo = {};
          try {
              dataInfo = JSON.parse(dataInfoStr);
          } catch (err) {
              jsInternalBridge.log("setCustomH5performanceData has error! ==>" + err);
              return;
          }
          const lengthLimitFileds = ['url'];
          const numberLimitFileds = ['imd', 'ns', 'ues', 'uee', 'rds', 'rde', 'fs', 'dls', 'dle', 'cs', 'scs', 'ce', 'reqs', 'rsps', 'rspe', 'dl', 'di', 'dcles', 'dclee', 'dc', 'les', 'lee', 'fp', 'fcp', 'lcp'];
          let normalStatus = true;
          if (normalStatus) {
              forEach(lengthLimitFileds, function (item) {
                  if (filterData(item, dataInfo[item], 'setCustomH5performanceData', MAX_LENGTH_1, false)) {
                      dataInfo[item]=set_length(dataInfo[item],MAX_LENGTH_1);
                  }
              });
          }
          if (normalStatus) {
              forEach(numberLimitFileds, function (item) {
                  if (filterData(item, dataInfo[item], 'setCustomH5performanceData', null, true)) {
                      normalStatus = false;
                      return normalStatus;
                  }
              });
          }
          if (!normalStatus) {
              return;
          }
          if (dataInfo.pvid === undefined || dataInfo.pvid === null || dataInfo.pvid === '' || dataInfo.pvid.length > MAX_LENGTH_2) {
              dataInfo.pvid = uuid();
          }
          dataInfo={url:dataInfo.url,pvid:dataInfo.pvid,ic:true,wpi:{
              ns:isDefined(dataInfo.ns)&&dataInfo.ns>0?dataInfo.ns:0,
              ues:isDefined(dataInfo.ues)&&dataInfo.ues>0?dataInfo.ues:-1,
              uee:isDefined(dataInfo.uee)&&dataInfo.uee>0?dataInfo.uee:-1,
              rds:isDefined(dataInfo.rds)&&dataInfo.rds>0?dataInfo.rds:-1,
              rde:isDefined(dataInfo.rde)&&dataInfo.rde>0?dataInfo.rde:-1,
              fs:isDefined(dataInfo.fs)&&dataInfo.fs>0?dataInfo.fs:0,
              dls:isDefined(dataInfo.dls)&&dataInfo.dls>0?dataInfo.dls:-1,
              dle:isDefined(dataInfo.dle)&&dataInfo.dle>0?dataInfo.dle:-1,
              cs:isDefined(dataInfo.cs)&&dataInfo.cs>0?dataInfo.cs:-1,
              scs:isDefined(dataInfo.scs)&&dataInfo.scs>0?dataInfo.scs:-1,
              ce:isDefined(dataInfo.ce)&&dataInfo.ce>0?dataInfo.ce:-1,
              reqs:isDefined(dataInfo.reqs)&&dataInfo.reqs>0?dataInfo.reqs:0,
              rsps:isDefined(dataInfo.rsps)&&dataInfo.rsps>0?dataInfo.rsps:0,
              rspe:isDefined(dataInfo.rspe)&&dataInfo.rspe>0?dataInfo.rspe:0,
              dl:isDefined(dataInfo.dl)&&dataInfo.dl>0?dataInfo.dl:0,
              di:isDefined(dataInfo.di)&&dataInfo.di>0?dataInfo.di:0,
              dcles:isDefined(dataInfo.dcles)&&dataInfo.dcles>0?dataInfo.dcles:0,
              dclee:isDefined(dataInfo.dclee)&&dataInfo.dclee>0?dataInfo.dclee:0,
              dc:isDefined(dataInfo.dc)&&dataInfo.dc>0?dataInfo.dc:0,
              les:isDefined(dataInfo.les)&&dataInfo.les>0?dataInfo.les:0,
              lee:isDefined(dataInfo.lee)&&dataInfo.lee>0?dataInfo.lee:-1,
              fp:isDefined(dataInfo.fp)&&dataInfo.fp>0?dataInfo.fp:-1,
              fcp:isDefined(dataInfo.fcp)&&dataInfo.fcp>0?dataInfo.fcp:-1,
              lcp:isDefined(dataInfo.lcp)&&dataInfo.lcp>0?dataInfo.lcp:-1,
              // imd:dataInfo.imd,
          }};
          if(!isDefined(dataInfo.url) || dataInfo.url.trim('')===''){
              return
          }
          if (isBrowser(GS.sett.osType) || isBrowser(GS.secondSett.osType)) {
              const performanceData = new Metric({ info: dataInfo }, GC.WEBVIEWDATA);
              performanceData.info('url','')
              .info('ic',true)
              .info('pvid')
              .info('wpi');
              pushQueueData(performanceData.build());
          }
          const resultAndroid = stringify({"h5":[{ent:now(),v:dataInfo,k:'h5'}],"imd":dataInfo.imd});
          const resultIos = stringify({ent:now(),v:dataInfo});
          jsInternalBridge.log("setCustomH5performanceData=> " + resultIos);
          try {
              if (isIOS(GS.sett.osType) || isIOS(GS.secondSett.osType)) {
                  window.webkit.messageHandlers.brsWKSetCustomH5performanceData.postMessage(resultIos);
                  return;
              }
              if(isHOS(GS.sett.osType) || isHOS(GS.secondSett.osType)){
                  window.bonreePrivateInterface.call(resultAndroid);
                  return;
              }
              window.bonreePrivateInterface.webViewEventBus(resultAndroid,GS.sett.webviewID  || GS.secondSett.webviewID);
          } catch (e) {
          }
      },
      setCustomRouteChangeData: function (dataInfoStr) {
          // 自定义路由切换数据
          let dataInfo = {};
          try {
              dataInfo = JSON.parse(dataInfoStr);
              dataInfo['d']=Math.round(dataInfo['d'])*1000;
          } catch (err) {
              jsInternalBridge.log("setCustomRouteChangeData has error! ==>" + err);
              return;
          }
          const lengthLimitFileds1 = ['tu', 'fu', 'rt', 'pu'];
          const lengthLimitFileds2 = ['pt', 'fw'];
          const numberLimitFileds = ['d', 'sta'];
          let normalStatus = true;
          if (normalStatus) {
              forEach(lengthLimitFileds1, function (item) {
                 if(!isDefined(dataInfo[item]) || dataInfo[item]==="" || dataInfo[item].length>MAX_LENGTH_1){
                      normalStatus=false;
                 }
              });
          }
          if (normalStatus) {
              forEach(lengthLimitFileds2, function (item) {
                  if(!isDefined(dataInfo[item]) || dataInfo[item]==="" || dataInfo[item].length>MAX_LENGTH_2){
                      normalStatus=false;
                   }
              });
          }
          if (normalStatus) {
              forEach(numberLimitFileds, function (item) {
                  if(!isDefined(dataInfo[item]) ||  typeof dataInfo[item]!=='number'){
                      normalStatus=false;
                   }
              });
          }
          if (!normalStatus) {
              return;
          }
          if (dataInfo.fu === undefined && dataInfo.fu === null) {
              jsInternalBridge.log("setCustomRouteChangeData Parameter has a value or key [fu] that does not exist!");
              return;
          }
          if (dataInfo.al !== undefined && dataInfo.al !== null) {
              if (dataInfo.al.length > MAX_LENGTH_2) {
                  jsInternalBridge.log("setCustomRouteChangeData Parameter has a value or key [al] that the value length exceeds " + MAX_LENGTH_2 + "!");
                  dataInfo.al = '';
              }
          }

          //赋值事件时间
          dataInfo.ent = new Date().getTime() * 1000;
              const routeData = new Metric({ info: dataInfo }, GC.ROUTE);
              routeData.info('tu', '')
                  .info('fu', '')
                  .info('d', 0)
                  .info('sta', 0)
                  .info('pt', '')
                  .info('rt', '')
                  .info('pu', '')
                  .info('fw', '')
                  .info('ic', true)
                  .info('ctp', 2)
                  .info('pvid',isDefined(GS.sett.pageViewId)?GS.sett.pageViewId:"");
                  if(isDefined(dataInfo['al'])&&dataInfo['al']!==''){
                      routeData.info('al','');
                  }
                  if(isDefined(window.performance)&&isDefined(window.performance.timing)){
                      routeData.info('ns',window.performance.timing.navigationStart);
                  }
              var RouteEvent=routeData.build();
              dataDevide(RouteEvent,jsInternalBridge.routeChangeData);
      },
      setCustomNetworkData: function (dataInfoString) {
          // 自定义网络数据
          let dataInfo = {};
          try {
              dataInfo = JSON.parse(dataInfoString);
          } catch (err) {
              jsInternalBridge.log("setCustomNetworkData has error! ==>" + err);
              return;
          }
          let normalStatus = true;
          let limit_1 = ['tp', 'dt', 'ct', 'sslt', 'rt', 'rti', 'dti', 'ds', 'pt', 'rds'];
          forEach(limit_1, function (item) {
              if (filterData(item, dataInfo[item], 'setCustomNetworkData', null, true) || dataInfo[item]<0 ) {
                  normalStatus = false;
                  return normalStatus;
              }
          });
          if (filterData('ti', dataInfo['ti'], 'setCustomNetworkData', null, false)) {
              normalStatus = false;
          }
          if(!isDefined(dataInfo['ru']) || dataInfo['ru']===""){
              return
          }
          if (filterData('ru', dataInfo['ru'], 'setCustomNetworkData', MAX_LENGTH_1, false)) {
              dataInfo['ru']=set_length(dataInfo['ru'],MAX_LENGTH_1);
          }
          if (filterData('m', dataInfo['m'], 'setCustomNetworkData', MAX_LENGTH_1, false)) {
              dataInfo["m"]=set_length(dataInfo["m"],MAX_LENGTH_1);
          }
          if (!normalStatus) {
              return;
          }
          //赋值事件时间
          dataInfo.ent = new Date().getTime() * 1000;
          const netData = new Metric({ info: dataInfo }, GC.NET);
          netData.info('ru', '')
              .info('m', '')
              .info('ti', '')
              .info('tp', 1000)
              .info('dt', 1000)
              .info('ct', 1000)
              .info('sslt', 1000)
              .info('rt', 1000)
              .info('rti', 1000)
              .info('dti', 1000)
              .info('ds', 0)
              .info('pt', 0)
              .info('rh', '')
              .info('rhe', '')
              .info('ret', '')
              .info('rds', 0)
              .info('id',uuid())
              .info('ic',true)
              .info('art',0)
              .info('ec',200);
          dataDevide(netData.build(),jsInternalBridge.NetworkEvent);
      },
      setCustomEventStart: function (eventId, eventName,eventLabel, eventParam,info) {
          if (arguments.length < 1 || arguments.length > 5) {
              return
          }
          if (filterData('eventId', eventId, 'setCustomEventStart', null, false)) {
              return;
          }
          if(isDefined(info)&&JSON.stringify(info).length>7000){
              return
          }
          if(includes(CustomEventExistQueue,eventId)){
              return
          }
          CustomEventExistQueue.push(eventId);
          if (arguments[0]) {
              /*自定义事件开始记录标识*/
              timeStampEvent[eventId]=dateNow();
              correlationId[eventId] = buildViewID();
              let onEventDic = {};
              let eventNameNew = set_length(eventName, MAX_LENGTH_2);
              let eventParamNew = set_length(eventParam,7000);
              onEventDic.eventId = isDefined(eventId) ? eventId : '';
              if(eventId.length>256 || eventId.length===0){
                  return
              }
              onEventDic.eventName = eventNameNew;
              onEventDic.eventParam = eventParamNew;
              onEventDic.eventLabel = set_length(eventLabel, 256);
              onEventDic.info=filterInfo(info);
              const eventData = new Metric({ info: onEventDic }, GC.CUSTOM_EVENT);
              eventData.info('eventId', '', 'i')
                  .info('t', 1)
                  .info('d', 0)
                  .info('ci', correlationId[eventId]);
                  if(onEventDic.eventName!==undefined&&onEventDic.eventName!==""){
                      eventData.info('eventName', '', 'n');
                  }
                  if(onEventDic.eventLabel!==undefined&&onEventDic.eventLabel!==""){
                      eventData.info('eventLabel', '', 'l');
                  }
                  if(onEventDic.eventParam!==undefined&&onEventDic.eventParam!==""){
                      eventData.info('eventParam', '', 'p');
                  }
                  if(onEventDic.info!==undefined&&onEventDic.info instanceof Object){
                      eventData.info('info', '', 'info');
                  }
              dataDevide(eventData.build(),jsInternalBridge.customEvent);
          }

      },
      setCustomEventEnd: function (eventId, eventName,eventLabel, eventParam,info) {
          if (arguments.length < 1 || arguments.length > 5) {
              return
          }
          if (filterData('eventId', eventId, 'setCustomEventEnd', null, false)) {
              return;
          }
          if(isDefined(info)&&JSON.stringify(info).length>7000){
              return
          }
          if(!includes(CustomEventExistQueue,eventId)){
              return
          }
          if (arguments[0]) {
              let d = 0;
              if (isDefined(dateNow) && timeStampEvent&&isDefined(timeStampEvent[eventId])) {
                  d = dateNow() - timeStampEvent[eventId];
                  d = d * 1000;
              }
              let onEventDic = {};
              let eventNameNew = set_length(eventName, MAX_LENGTH_2);
              let eventParamNew = set_length(eventParam, 7000);
              onEventDic.eventId = isDefined(eventId) ? eventId : '';
              if(eventId.length>256 || eventId.length===0){
                  return
              }
              onEventDic.eventName = eventNameNew;
              onEventDic.eventParam = eventParamNew;
              onEventDic.eventLabel = set_length(eventLabel, 256);
              onEventDic.info = filterInfo(info);
              const eventData = new Metric({ info: onEventDic }, GC.CUSTOM_EVENT);
              eventData.info('eventId', '', 'i')
                  .info('t', 2)
                  .info('d', d)
                  .info('ci',correlationId[eventId]);
                  if(onEventDic.eventName!==undefined&&onEventDic.eventName!==""){
                      eventData.info('eventName', '', 'n');
                  }
                  if(onEventDic.eventLabel!==undefined&&onEventDic.eventLabel!==""){
                      eventData.info('eventLabel', '', 'l');
                  }
                  if(onEventDic.eventParam!==undefined&&onEventDic.eventParam!==""){
                      eventData.info('eventParam', '', 'p');
                  }
                  if(onEventDic.info!==undefined&&onEventDic.info instanceof Object){
                      eventData.info('info', '', 'info');
                  }
              dataDevide(eventData.build(),jsInternalBridge.customEvent);
          }
          CustomEventExistQueue=filter(CustomEventExistQueue,function(item){return item !==eventId});
          delete timeStampEvent[eventId];
          delete correlationId[eventId];
      },
      startSpan:function(name,type){
          return new SpanStruct(name,type)
      }
  };

  class FunAction{
      constructor(fn){
          this.n=fn&&typeof(fn) ==="string"?fn:fn.name;
          this.t=12;
          this.to=false;
          this.ice=false;
          this.st=1;
          this.et=0;
          this.ti=1225;
          this.im=true;
          this.ne={};
      }
      funActionModify=function(tag,data){
          if(isDefined(tag)&&isDefined(data)){
              this[tag]=data;
          }
          return this
      }
      funActionBuild=function(){
          var ActionBuild= {
              n:this.n,
              t:this.t,
              to:this.to,
              ice:this.ice,
              st:this.st,
              et:this.et||now(),
              ti:this.ti,
              im:this.im,
              ne:this.ne
          };
          if(isEmpty(ActionBuild.ne)){
              delete ActionBuild.ne;
          }
          return ActionBuild
      }

  }

  /**
   * 获取事件源的xpath路径
   * @param {*} e 
   * @return xpath字符串
   */
  function getXpath(e) {
      if (!isDefined(e)) {
        return ''
      }
      if (e.$xpath) {
        return e.$xpath
      }
      var pathStr = xpath(e);
      if (pathStr.length > 200) {
        e.$xpath = '[Error: Overflow with more than 200 characters.]';
      } else {
        e.$xpath = pathStr;
      }
      return e.$xpath
  }
  /**
   * @descripe 结束事件处理
   * @param {*} event 回调参数event
   **/
  function actionEnd(event,isCustomEnd=false){
      if(!isDefined(event)){
          return
      }
      /*清除定时器*/
      // 强制关闭定时器
      if(isDefined(event.$timeoutTimer)){
          clearTimeout(event.$timeoutTimer);
      }
      // 网络监听
      notifierRemove(GC.LIFESTYLE_REQUEST_END+event.identify);
      // 客户主动触发结束
      notifierRemove(GC.CUSTOM_ACTION_END);
      // 网络回调事件
      notifierRemove(GC.LIFESTYLE_CALLBACK_REQUEST_START+event.identify);
      // 路由切换结束
      notifierRemove(GC.ROUTE_CHANGE_END+event.identify);
      // websocket连接结束
      notifierRemove(GC.WEBSOCKET_CONNECTION_END);
      // ？
      notifierRemove(GC.SPAN_CALLBACK_DATA);
      // 根节点
      let rootMethod=new FunAction('anonymous');
      // 设置开始时间
      rootMethod.funActionModify('st',event.startTime);
      // 设置结束时间
      rootMethod.funActionModify('et',event.endTime);
      // 如果是客户自定义结束
      if(isCustomEnd){
          // 设置客户自定义标识
          rootMethod.funActionModify('ice',true);
          // 计算事件耗时
          event.startEvent.lt=event.endTime-event.startTime;
          // 开始事件设置自定义标识
          event.startEvent.ice=true;
          //hasEmitStart 是否上报过开始，如果没有就上报开始，如果上报过，就不再执行
          if(isDefined(event.hasEmitStart)&&!event.hasEmitStart){
              /*前置配置*/
              notifierEmit({t:GC.TRACE_ACTION_DATA,p:{info:event.startEvent},type:1});
              /*后置配置*/
              if(!isEmpty(GS.secondSett)){
                  notifierEmit({t:GC.TRACE_ACTION_DATA,p:{info:event.startEvent},type:2});
              }
              /*标识是否上报过开始*/
              event.hasEmitStart=true;
          } 
      }
      // 定义结束事件，合并开始事件
      let endEvent=extend({},event.startEvent);
      // m为2是结束事件？
      endEvent.m=2;
      // 构建事件
      endEvent.me=rootMethod.funActionBuild();
      /*前置配置*/
      notifierEmit({t:GC.TRACE_ACTION_DATA,p:{info:endEvent},revts:event.handledRequestStruct,type:1});
      /*后置配置*/
      if(!isEmpty(GS.secondSett)){
          notifierEmit({t:GC.TRACE_ACTION_DATA,p:{info:endEvent},revts:event.handledRequestStructSecond,type:2});
      }
  }
  /**
   * @descripe 捕获阶段获取基础信息组包点击开始事件准备上报,因为有的元素无冒泡阶段
   * 此时以该默认值上报,lt无法获取
   **/
  function capturePeriod(event){
      try {
          /*避免无冒泡阶段自定义结束订阅未移除*/
          notifierRemove(GC.CUSTOM_ACTION_END);
          /*点击开始时间等,挂载供冒泡阶段方便获取*/
          let startTime=now();
          event.startTime=startTime;
          event.requestRecord=[];
          /*存储前置配置revts*/
          event.handledRequestStruct=[];
          /*存储后置配置revts*/
          event.handledRequestStructSecond=[];
          // 请求计数
          event.requestCount=0;
          // 路由计数
          event.routeCount=0;
          // websocket计数
          event.wsCount=0;
          event.identify=uuid();
          /*前置配置路由关联的网络事件*/
          event.handledRouteRequest=[];
          /*后置配置路由关联的网络事件*/
          event.handledRouteRequestSecond=[];
          /*span数据*/
          event.handledSpan=[];
          notifierOn(GC.ROUTE_CHANGE_START,function(ext){
              event.routeCount=event.routeCount+1;
              /*点击是否关联路由*/
              event.relatedRoute=true;
              /*给路由关联上actionid*/
              ext.info.id=event.identify;
          });
          notifierOn(GC.ROUTE_CHANGE_END+event.identify,function(ext){
              event.routeCount=event.routeCount-1;
              /*前置revts处理*/
              if(isDefined(ext.routeData)&&event.relatedRoute&&event.handledRouteRequest.length>0&&event.routeCount===0){
                  let routeData=JSON.parse(JSON.stringify(ext.routeData));
                  routeData.revts=event.handledRouteRequest;
                  event.handledRequestStruct.push(routeData);
              }else {
                  event.handledRequestStruct.push(ext.routeData);
              }
              /*后置revts配置处理*/
              if(!isEmpty(GS.secondSett)){
                  if(checkMoudle('routechange')){
                      if(isDefined(ext.routeData)&&event.relatedRoute&&event.handledRouteRequestSecond.length>0&&event.routeCount===0){
                          let routeData=JSON.parse(JSON.stringify(ext.routeData));
                          routeData.revts=event.handledRouteRequestSecond;
                          event.handledRequestStructSecond.push(routeData);
                      }else {
                          event.handledRequestStructSecond.push(ext.routeData);
                      }
                  } 
              }

              // 如果开始已经上报了，并且这里没有网络请求和websocket就移除对应的监听,并且结束action事件
              if(event.hasEmitStart&&event.requestCount===0&&event.wsCount===0){
                  notifierRemove(GC.LIFESTYLE_REQUEST_END+event.identify);
                  notifierRemove(GC.LIFESTYLE_CALLBACK_REQUEST_START+event.identify);
                  notifierRemove(GC.ROUTE_CHANGE_END+event.identify);
                  notifierRemove(GC.WEBSOCKET_CONNECTION_END);
                  actionEnd(event);
              }
          });
          // fetch网络请求关联事件id
          notifierOn(GC.LIFESTYLE_FETCH_START,function(ext){
              /*给触发的请求关联上id*/
              if(isDefined(ext.info)){
                  ext.info.ai=event.identify;
              }
              // 网络请求记录里面记录当前发生网络请求的时间节点
              event.requestRecord.push(now());
              // 网络请求的数量加1
              event.requestCount=event.requestCount+1;
          });
          // 同fetch设计原理
          notifierOn(GC.LIFESTYLE_XHR_START,function(ext){
              /*给触发的请求关联上id*/
              if(isDefined(ext.info)){
                  ext.info.ai=event.identify;
              }
              event.requestRecord.push(now());
              event.requestCount=event.requestCount+1;
          });
          // 网络请求回调里再次触发网络请求
          notifierOn(GC.LIFESTYLE_CALLBACK_REQUEST_START+event.identify,function(ext){
                  event.requestCount=event.requestCount+1;
          });
          // 网络请求结束
          notifierOn(GC.LIFESTYLE_REQUEST_END+event.identify,function(ext){
              // 请求总数减1
              event.requestCount=event.requestCount-1;
              /*revts处理*/
              // 不是路由触发的网络请求
              if(isDefined(ext)&&isDefined(ext.requestData)&&isDefined(ext.endTime)&&!event.relatedRoute){
                  let settRequestEvent=requestService(ext.requestData,GS.sett,true);
                  /*前置配置处理*/
                  event.handledRequestStruct.push({k:settRequestEvent.type,ent:settRequestEvent.ent,sin:settRequestEvent.sin,v:settRequestEvent.data});
                  /*后置配置处理*/
                  if(!isEmpty(GS.secondSett)){
                      if(checkMoudle('network')){
                          let settSecondRequestEvent=requestService(ext.requestData,GS.secondSett,true);
                          event.handledRequestStructSecond.push({k:settSecondRequestEvent.type,ent:settSecondRequestEvent.ent,sin:settSecondRequestEvent.sin,v:settSecondRequestEvent.data}); 
                      }
                  }
              }
              /*路由关联的网络事件处理,若触发了路由就存储*/
              if(event.relatedRoute){
                  let settRequestEvent=requestService(ext.requestData,GS.sett,true);
                  /*前置配置处理*/
                  event.handledRouteRequest.push({k:settRequestEvent.type,ent:settRequestEvent.ent,sin:settRequestEvent.sin,v:settRequestEvent.data});

                  /*后置配置处理*/
                  if(!isEmpty(GS.secondSett)){
                      if(checkMoudle('network')){
                          let settSecondRequestEvent=requestService(ext.requestData,GS.secondSett,true);
                          event.handledRouteRequestSecond.push({k:settSecondRequestEvent.type,ent:settSecondRequestEvent.ent,sin:settSecondRequestEvent.sin,v:settSecondRequestEvent.data}); 
                      }
                  }
              }
              /*request回调已经全部完成,组结束action,移除订阅*/
              // 结束action
              if(event.requestCount===0&&event.routeCount===0&&event.wsCount===0){
                  notifierRemove(GC.LIFESTYLE_REQUEST_END+event.identify);
                  notifierRemove(GC.LIFESTYLE_CALLBACK_REQUEST_START+event.identify);
                  notifierRemove(GC.ROUTE_CHANGE_END+event.identify);
                  notifierRemove(GC.WEBSOCKET_CONNECTION_END);
                  if(isDefined(event.loadTime)){
                      actionEnd(event);
                  }
                  pageActivityManager.turnOffRecord();
                  pageActivityManager.stopPageActivityObserver();
              }
          });
          // 自定义结束
          notifierOn(GC.CUSTOM_ACTION_END,function(ext){
              /*挂载自定义结束时间*/
              event.endTime=now();
              actionEnd(event,true);
          });
          // span回调数据
          // 如果存在websocket数据，标明span数据跟websocket数据关联了
          notifierOn(GC.SPAN_CALLBACK_DATA,function(ext){
              if(isDefined(ext.websocketData)){
                  const {type:k,ent:ent,sin:sin,data:v}=ext.websocketData;
                  /*标识该span数据关联了*/
                  ext.websocketData.isRelated=true;
                  // 前置配置插入数据？？
                  event.handledRequestStruct.push({k,ent,sin,v});
                  //检查端上的配置是否有span的配置，有则上报
                  if(checkMoudle('span')){
                      event.handledRequestStructSecond.push({k,ent,sin,v});
                  }
                  /*放到span中,未命中action采集时上报*/
                  event.handledSpan.push(ext.websocketData);
              }
          });
          // websocket连接开始，wbsocket的数量+1
          notifierOn(GC.WEBSOCKET_CONNECTION_START,function(){
              event.wsCount=event.wsCount+1;
          });
          // websocket的连接结束，数量减1，actionn事件结束，移除没有待定事件的监听
          notifierOn(GC.WEBSOCKET_CONNECTION_END,function(){
              event.wsCount=event.wsCount-1;
              if(event.requestCount===0&&event.routeCount===0&&event.wsCount===0){
                  notifierRemove(GC.LIFESTYLE_REQUEST_END+event.identify);
                  notifierRemove(GC.LIFESTYLE_CALLBACK_REQUEST_START+event.identify);
                  notifierRemove(GC.ROUTE_CHANGE_END+event.identify);
                  notifierRemove(GC.WEBSOCKET_CONNECTION_END);
                  actionEnd(event);
              }
          });
          /*脱敏url(vn)*/
          GS.sett.pageUrl=sensitiveRuleHandle({
              p:{
                  info:{
                      url:isDefined(window.location)?window.location.href:""
                  }
              }
          },GS.sett).p.info.url;
          /*开启页面激活管理(resource/DOM变化记录)*/
          if(isDefined(pageActivityManager)){
              pageActivityManager.startPageActivityObserver();
              pageActivityManager.turnOnRecord();
          } 
          let target=event.target;
          var tagType = isString(target.tagName) || target.name||'';
          if(tagType==="BODY"){
              return
          }
          let xpathInfo=`xpath`+unicode('=')+`${getXpath(target)}`+`,outerHTML`+unicode('=')+`${target.outerHTML}`;
          let type=event&&event.type==="click"&&1||4;
          let name=event&&event.target&&event.target.tagName||'';
          let controlInformation={
              t:getActionText(target)||target.innerText||'',
              c:String(target.className||''),
              tag:target.nodeName||target.localName||'',
              id:isDefined(target.id)?target.id:''
          };
          let href=GS.sett.pageUrl;
          event.startEvent={
              t:type,
              n:name,
              sa:1,
              i:xpathInfo,
              vn:href,
              ic:false,
              lt:0,
              is:false,
              id:event.identify,
              m:1,
              ice:false,
              ci:controlInformation,
              timestamp:startTime,
              vci:GS.sett.pageViewId
          };
          /*
          *100ms后判断该点击是否命中有效条件1:点击后有resource加载;2:点击后有DOM树变化;3:点击后有网络请求发出
          */
          event.$startTimer= setTimeout(function (){
              if(!isDefined(pageActivityManager) || !isDefined(checkRecord)){
                  return
              }
              if(checkRecord(pageActivityManager.mutationRecord,startTime) || checkRecord(pageActivityManager.performanceRecord,startTime) || checkRecord(event.requestRecord,startTime)){
                  /*前置配置*/
                  notifierEmit({
                      t:GC.TRACE_ACTION_DATA,
                      p:{
                          info:event.startEvent
                      },
                      type:1
                  });
                  /*后置配置*/
                  if(!isEmpty(GS.secondSett)){
                      notifierEmit({t:GC.TRACE_ACTION_DATA,p:{info:event.startEvent},type:2});
                  }
                  /*说明没有冒泡阶段*/
                  notifierRemove(GC.LIFESTYLE_REQUEST_END+event.identify);
                  notifierRemove(GC.LIFESTYLE_FETCH_START); // 
                  notifierRemove(GC.LIFESTYLE_XHR_START);
                  notifierRemove(GC.CUSTOM_ACTION_END);
                  notifierRemove(GC.LIFESTYLE_CALLBACK_REQUEST_START+event.identify);
                  notifierRemove(GC.ROUTE_CHANGE_START);
                  notifierRemove(GC.ROUTE_CHANGE_END+event.identify);
                  notifierRemove(GC.SPAN_CALLBACK_DATA);
                  notifierRemove(GC.WEBSOCKET_CONNECTION_START);
                  notifierRemove(GC.WEBSOCKET_CONNECTION_END);
                  pageActivityManager.turnOffRecord();
                  pageActivityManager.stopPageActivityObserver();
                  /*标识是否上报过开始*/
                  event.hasEmitStart=true;
              }else {
                  /*未命中直接舍弃*/
                  notifierRemove(GC.LIFESTYLE_REQUEST_END+event.identify);
                  notifierRemove(GC.LIFESTYLE_FETCH_START);
                  notifierRemove(GC.LIFESTYLE_XHR_START);
                  notifierRemove(GC.CUSTOM_ACTION_END);
                  notifierRemove(GC.LIFESTYLE_CALLBACK_REQUEST_START+event.identify);
                  notifierRemove(GC.ROUTE_CHANGE_START);
                  notifierRemove(GC.ROUTE_CHANGE_END+event.identify);
                  notifierRemove(GC.SPAN_CALLBACK_DATA);
                  notifierRemove(GC.WEBSOCKET_CONNECTION_START);
                  notifierRemove(GC.WEBSOCKET_CONNECTION_END);
                  pageActivityManager.turnOffRecord();
                  pageActivityManager.stopPageActivityObserver();
              }
          },1000);
      } catch (error) {
          log('C151'); 
      }
  }
  /**
   * @descripe 冒泡阶段开始事件获取lt上报,准备结束事件上报
   **/
  function bubblingPeriod(event){
      try {
          let endTime=now();
          /*此时绑定方法执行完*/
          if(isDefined(event.$startTimer)){
              clearTimeout(event.$startTimer);
          }
          /*到此阶段该点击下的网络开始方法已经执行过*/
          // 清除已经执行过的监听
          notifierRemove(GC.LIFESTYLE_FETCH_START);
          notifierRemove(GC.LIFESTYLE_XHR_START);
          notifierRemove(GC.ROUTE_CHANGE_START);
          notifierRemove(GC.WEBSOCKET_CONNECTION_START);
          // 耗时计算
          let loadTime=endTime-event.startTime;
          event.loadTime=loadTime;
          event.endTime=endTime;
          /*request与DOM变化回调非常快,reource回调可能会有延迟,实际使用场景点击链接只有script/link资源加载
          场景几乎没有,故暂无需考虑延时去判断是否有效点击
          */
          if(!isDefined(pageActivityManager)){
              return
          }

          // qqq !isEmpty(event.startEvent) 增加这个条件来放宽action的上报限制  !isEmpty(event.startEvent)|| 
          if(!event.hasEmitStart&&(event.requestRecord.length>0 || checkRecord(pageActivityManager.mutationRecord,event.startTime) || checkRecord(pageActivityManager.performanceRecord,event.startTime))){
              event.startEvent['lt']=loadTime;
              /**前置配置处理*/
              notifierEmit({t:GC.TRACE_ACTION_DATA,p:{info:event.startEvent},type:1});
              /*后置配置*/
              if(!isEmpty(GS.secondSett)){
                  notifierEmit({t:GC.TRACE_ACTION_DATA,p:{info:event.startEvent},type:2}); 
              }
              event.hasEmitStart=true;
              /*超时30s未闭包时强制闭包*/
              event.$timeoutTimer=setTimeout(function(){
                  actionEnd(event);
              },120*1000);
              /*根据回调完全是否处理结束点击事件*/
              if(event.requestCount===0&&event.routeCount===0&&event.wsCount===0){
                  actionEnd(event);
              }
              pageActivityManager.turnOffRecord();
              pageActivityManager.stopPageActivityObserver();
          }else {
              /*未命中action采集时处理span*/
              if(event.handledSpan.length>0){
                  for(let span of event.handledSpan){
                      dataDevide(span,jsInternalBridge.spanEvent);
                  }
              }
              /*没有命中操作分析条件清除注册*/
              notifierRemove(GC.LIFESTYLE_REQUEST_END+event.identify);
              notifierRemove(GC.CUSTOM_ACTION_END);
              notifierRemove(GC.LIFESTYLE_CALLBACK_REQUEST_START+event.identify);
              notifierRemove(GC.ROUTE_CHANGE_END+event.identify);
              notifierRemove(GC.WEBSOCKET_CONNECTION_END);
              notifierRemove(GC.SPAN_CALLBACK_DATA);
          }
          return
      }catch(err){
          log('C152'); 
      }
  }
  function recordCustomActionEnd(){
      notifierEmit({t:GC.CUSTOM_ACTION_END});
  }
  function initActionCollector() {
      /*捕获阶段,事件流程是捕获阶段-目标阶段(绑定方法执行)-冒泡阶段*/
      on$1(window, 'click', capturePeriod, true);
      /*冒泡阶段*/
      // 这里的逻辑是在冒泡阶段可能有网络请求，这个时候直接组包有可能没有网络数据挂载的情况
      on$1(window, 'click', (event)=>setTimeout(()=>bubblingPeriod(event),50), false);
  }

  // 防抖
  function Debouncer(onsubmit, period) {
    this.lastTimer = null;
    this.lastEvent = null;
    this.period = period || 1000;
    this.compare = function () { return false };
    this.submit = onsubmit || NIL_FN;
  }

  extend(Debouncer.prototype, {
    // 防抖实现
    $schedule: function (evt) {
      if (isDefined(this.lastTimer)) {
        clearTimeout(this.lastTimer);
      }
      var $this = this;
      this.lastEvent = evt;
      this.lastTimer = delay(function () {
        $this.submit($this.lastEvent);
        $this.lastEvent = null;
      }, this.period);
    },
    // 判断lastEvent和evt是否是同一数据，如果是，旧数据添加到新的evt里面，如果不是同一个数据源，上报lastEvent，并将新的evt添加到防抖执行函数里
    event: function (evt) {
      if (isDefined(this.lastEvent)) {
        if (this.compare(this.lastEvent, evt)) {
          evt.info[GC.DURATION] = evt.info[GC.START_TIME] - this.lastEvent.info[GC.START_TIME];
          evt.info[GC.TIMESTAMP] = this.lastEvent.info[GC.TIMESTAMP];
          evt.info[GC.START_TIME] = this.lastEvent.info[GC.START_TIME];
          evt.info.count = this.lastEvent.info.count + 1;
        } else {
          this.submit(this.lastEvent);
        }
      }
      this.$schedule(evt);
    },
    // 清空现有的发送行为
    flush: function () {
      if (isDefined(this.lastTimer)) {
        clearTimeout(this.lastTimer);
        this.lastTimer = null;
      }
      if (isDefined(this.lastEvent)) {
        this.submit(this.lastEvent);
        this.lastEvent = null;
      }
    },
    equalsWith: function (cb) {
      if ('apply' in cb) {
        this.compare = cb;
      }
    }
  });

  /*
  error对象没有line,col信息补充从堆栈中获取
  */
  function extendFromStack (info, stack, inner) {
    if (!isReadable(info.file) && stack) {
      try {
        var STACK_REG = /[@(\s]+?([\S]+):(\d+):(\d+)\)?/;
        var STACK_LEGACY_FIREFOX = /[@(\s]+?([\S]+):(\d+)\)?/;
        var MATCH_REG = /([^@(\s)]+):(\d+):(\d+)/;
        var MATCH_LEGACY_REG = /([^@(\s)]+):(\d+)/;
        var locations = stack.split('\n');
        var item;
        var firstMatch = true;
        var getNumber=function (str) {
          var num = Number(str);
          return isNaN(num) ? 0 : num
      };
        for (var i = 0; i < locations.length; i++) {
          item = locations[i];
          var matched = STACK_REG.test(item) || STACK_LEGACY_FIREFOX.test(item);
          if (matched) {
            if (firstMatch && inner) {
              firstMatch = false;
              locations[i] = '';
            } else {
              var toMatch = last(item.split(/\s+/));
              var matches = MATCH_REG.exec(toMatch) || MATCH_LEGACY_REG.exec(toMatch);
              info.file = matches[1].replace(/^\(/, '');
              info.line = getNumber(matches[2]);
              info.column = getNumber(matches[3]);

              break
            }
          }
        }
        if (inner) {
          info.stack = locations.join('\n')
            .replace(/\n+/g, '\n')
            .replace(/^\n/, '');
        }
      } catch (e) {
        log('C146');
      }

      return info
    }
  }

  /*
  从error对像获取信息赋予info
  */
  function extendFromError (info, err, inner) {
    if (!isDefined(err)) {
      return info
    }
    
    var type = err.name || (err.constructor && err.constructor.name);
    info.name = type&&toString$2(type) || '';
    if (!isReadable(info.message)) {
      info.message = (isReadable(type) ? type + ': ' : '') + err.message;
    }

    if (!isReadable(info.file)) {
      info.file = err.fileName;
    }

    if (!isDefined(info.line)) {
      info.line = err.lineNumber;
      info.column = err.columnNumber;
    }

    info.stack = err.stack;
    extendFromStack(info, info.stack, inner);

    return info
  }

  // 防抖
  var debouncer = new Debouncer(function (info) {
    notifierEmit({ t: GC.ERROR_DATA, p: info });
  }, GS.sett.debounce);
  // 定义判定相等的防抖函数方法，来实现compare的比较
  debouncer.equalsWith(function (pre, next) {
    var errorIndex=function (e) {
      return e.message + e.line + e.column
    };
    var indexPre = errorIndex(pre.info);
    var indexNext = errorIndex(next.info);
    return indexPre === indexNext
  });
  /*
  提交error信息,将info交给debouncer回调处理
  */
  function submitError (info, ext) {
      var errorData = {
        info: extend(info, {
          message: withLength(info.message, 200),
          duration: 0,
          type: isDefined(info.type) ? info.type : 0,
          count: 1,
          file: withLength(info.file, 200) || '<anonymous>',
          stack: withLength(info.stack, 5000)
        })
      };
      if (isDefined(ext)) {
        errorData.ext = ext;
      }
      debouncer.event(errorData);
    }
  // 监听FLUSH_DATA，清除当前防抖上报数据行为
  notifierOn(GC.FLUSH_DATA, function () {
    debouncer.flush();
  });

  /*常规jserror采集,hack是因为onerror只能声明一次*/
  function hackError () {
    window.onerror = hack(window.onerror, function (msg, src, lineno, colno, error) {
      var info = extend({
        message: msg,
        line: lineno,
        column: colno,
        file: src,
        type:3
      }, getTime());
      extendFromError(info, error);
      submitError(info);
    });
  }
  /*jserror采集初始化*/
  function initError() {
      hackError();
      notifierOn(GC.PAGE_READY, function () {
        hackError();
      });
      /*资源类的error处理*/
      addListener(window, 'error', function (e) {
        var target = e.target||e.srcElement;
        if (isDefined(target) && (target instanceof HTMLScriptElement || target instanceof HTMLLinkElement || target instanceof HTMLImageElement)) {
          notifierEmit({
            t: GC.ERROR_DATA,
            p: {
              info: extend({
                message: xpath(target),
                duration: 0,
                type: 1,
                count: 1,
                file: withLength((target.src||e.filename), 200),
                line: 0,
                column: 0,
                stack: ''
              }, getTime())
            }
          });
        }
      }, true);
      /*promise类的error采集*/
      addListener(window, 'unhandledrejection', function (e) {
        if (!isDefined(e)) {
          return
        }
        if (isString(e.reason)) {
          var info = extend({
            message: e.reason,
            line: 0,
            column: 0
          }, getTime());
          /*ect字段*/
          if(isDefined(e.type)){
            info.type=2;
          }
          submitError(info);
        } else {
          error(e.reason);
        }
      }, true);
    }
  /*error(string,object)等自定义处理*/
  function error(err) {
      if (!isDefined(err)) {
        return log('C122')
      }
      // 获取时间，{当前时间，当前时间+加载起始时间}
      var info = getTime();
      var ext;
      if (typeof err === 'string') {
        info.message = err;
        err = new Error(err);
        extendFromError(info, err, true);
      } else if (window.ErrorEvent && err instanceof ErrorEvent) { /* global ErrorEvent */
        extend(info, {
          message: err.message,
          line: err.lineno,
          column: err.colno,
          file: err.filename
        });
    
        extendFromError(info, err.error);
        if (!isReadable(info.file)) {
          if (err.target) {
            info.file = err.target.baseURI;
          }
        }
      } else {
        /*Error-like Object*/
        extendFromError(info, err);
        if (typeof err.type === 'number') {
          info.type = err.type;
        }else {
          info.type=3;
        }
        ext = err.ext;
      }
    
      submitError(info, ext);
    }

  function initConsole(){
    if (console&&console.error) {
        console.error= hackConsole(console.error, null, errorHandler);
    }
  }
  function hackConsole (fn, before, after) {
    if (fn.$original) {//防止与log 探针冲突及防止重复hook
      return fn
    }
    var hackedFn = function () {
      var params = args(arguments);
      try {
        if (isDefined(before)) {
          before.apply(this, params);
        }
        if(params[0] instanceof Error){
          error(params[0]);
        }
        return fn.apply(this, params)
      } catch (e) {
        throw e
      } finally {
        after.apply(this, params);
      }
    };
    hackedFn.$original = fn;
    return hackedFn
  }
  function errorHandler() {
      if (console['$bonree']) {
        return
      }
      const parmas = args(arguments);
      const strParmas = formatArg(parmas);
      const consoleEvent={
          'lv':'error',
          'msg':strParmas
      };
      notifierEmit({ t: GC.CONSOLE_DATA, p: { info: consoleEvent } });
  }
  /*将console.error()参数字符串化*/
  function formatArg(arr) {
    // let str=arr.map(o => JSON.stringify(o)).join(", ")
    if (arr && isArray(arr)) {
      const arry = map(arr, function (item) {
        if (typeof item === 'undefined') {
          // eslint-disable-next-line no-param-reassign
          item = String(item);
        }
        const strItem = formatMessage(item);
        return strItem
      });
      return arry.join(' ')
    }
    return arr
  }
  function formatMessage(message) {
    let msg;
    if (isString(message)) {
      return message
    }
    if (message instanceof Error || message instanceof Function) {
      return String(message)
    }
    try {
      msg = stringify(message);
    } catch (e) {
      msg = String(message);
    }
    return msg
  }

  var synced = false;
  var longTaskEntries=[];
  var resources = [];
  let FP;
  let FCP;
  let LCP;
  /*h5关联网络事件*/
  var h5RelatedEvents=[];
  /*h5关联网络事件(后置配置)*/
  var h5RelatedEventsSecond=[];
  /*标识是否是在onload采集*/
  var specialCollect=false;

  /*记录页面开始到onload请求数*/
  var requestCount=0;

  // 利用 window.PerformanceObserver API 获取渲染时间
  function listenForPaintMetrics() {
      if (!isDefined(window.PerformanceObserver)) { /* global PerformanceObserver */
        return log('C113')
      }
      var observer = new PerformanceObserver(function (entryList) {
        var entries = entryList.getEntries();
        forEach(entries, function (ent) {
          if (ent.name === 'first-paint ') {
            FP = ent[GC.START_TIME] && ent[GC.START_TIME] || '';
          }
          if (ent.name === 'first-contentful-paint') {
            FCP = ent[GC.START_TIME] && ent[GC.START_TIME] || '';
          }
          if (ent.entryType === 'largest-contentful-paint') {
            LCP = ent.renderTime || ent.loadTime||'';
          }
        });
      });
      try {
        observer.observe({ entryTypes: ['paint', 'largest-contentful-paint'] });
      } catch (e) {
        log('C114');
      }
  }

  // 兼容ie和低版本浏览器
  function getPaintMetrics(metric) {
      if (!globalData.state) {
        return log('C110')
      }
      if (!isDefined(FP) || !isDefined(FCP)) {
        if (window.performance.getEntriesByType) {
          forEach(window.performance.getEntriesByType('paint'), function (ent) {
            if (ent.name === 'first-paint') {
              FP = ent[GC.START_TIME] && ent[GC.START_TIME] || 0;
            }
            if (ent.name === 'first-contentful-paint') {
              FCP = ent[GC.START_TIME] && ent[GC.START_TIME] || 0;
            }
          });
        }
      }
      if (!isDefined(FP)) {
        var timing = window.performance.timing;
        var start = timing[GC.NAVIGATION_START];
        if (timing.msFirstPaint) {
          log('C111');
          FP = timing.msFirstPaint - start;
        }
        if (window.chrome && window.chrome.loadTimes) {
          var times = window.chrome.loadTimes();
          if (times && times.firstPaintTime) {
            log('C112');
            FP = times.firstPaintTime - start;
          }
        }
      }
      return {
        fp: FP ? Math.round(FP) : 0,
        fcp: FCP ? Math.round(FCP) : 0,
        lcp: LCP ? Math.round(LCP) : 0
      }
  }

  function getRelativePeriod(end, start) {
      return end > 0 ? (end - start) : 0
  }
  function getResourceLoadTime() {
      const performance = window.performance || window.msPerformance || window.webkitPerformance;
      var resourceData = performance.getEntriesByType('resource')||[];
      if(resourceData.length===0){
          return isDefined(performance.timing)?(performance.timing[GC.LOAD_EVENT_END]-performance.timing[GC.NAVIGATION_START]>0?performance.timing[GC.LOAD_EVENT_END]-performance.timing[GC.NAVIGATION_START]:0):10
      }
      var resourceLoadTimeArr = map(resourceData,function (item) {
        return item.responseEnd
      });
      // 对数组排序，获取资源加载最长的时间
      var sortArr = resourceLoadTimeArr.sort((a, b) => b - a);
      var max = Math.round(sortArr[0]);
      return max
  }



  function onload() {
        GS.setData('pageUrl',sensitiveRuleHandle({p:{info:{url:GS.sett.pageUrl}}},GS.sett).p.info.url);
        notifierEmit({ t: GC.PAGE_LOAD });
        getlongtask();
        delay(checkMetrics, 1000);
  }

  function checkMetrics(sync) {
      if (!synced) {
        synced = true;
        /*type:1主文档性能数据(wpi) type:2资源性能数据(wri)*/
        notifierEmit({ t: GC.RESOURCE_DATA, p: getAllPageMetrics(),type:1});
        notifierEmit({ t: GC.RESOURCE_DATA, p: getResourceMetrics(),type:2,special:specialCollect});
        /*onload之前发起的网络回调完毕*/
       if(requestCount===0){
          notifierRemove(GC.LIFESTYLE_XHR_START);
          notifierRemove(GC.LIFESTYLE_FETCH_START);
          notifierRemove(GC.LIFESTYLE_REQUEST_END+"H5");
          notifierEmit({ t: GC.RESOURCE_DATA,p:{},type:3,revts:h5RelatedEvents});
          /*后置配置生成revts*/
          if(!isEmpty(GS.secondSett)){
            notifierEmit({ t: GC.RESOURCE_DATA,p:{},type:4,revts:h5RelatedEventsSecond});
          }
         }
      }
      notifierEmit({ t: GC.FLUSH_DATA, p: !!sync });
  }

  // 获取resource资源
  function getResourceMetrics() {
      if (!window.performance || !window.performance.getEntriesByType) {
        log('C116');
        return []
      }
      var items = resources.concat(window.performance.getEntriesByType('resource'));
      resources = [];
      var datas = map(items, function (item) {
        var type = item[GC.INITIATOR_TYPE];
        var entryType = item['entryType'];
        let ret=getMineTypeByUrl(item['name']);
        if (isDefined(item.name)&&item.name.indexOf(GS.sett.uploadAddrHttps)===-1 || isDefined(item.name)&&item.name.indexOf(GS.sett.uploadAddrHttp)===-1) {
          var resourceInfo = {};
          var resourceMetric = {};
          resourceInfo.name = sensitiveRuleHandle({p:{info:{url:item.name}}},GS.sett).p.info.url;
          resourceInfo[GC.START_TIME] = getFixedMetric(item, GC.START_TIME);
          resourceInfo[GC.INITIATOR_TYPE] = type;
          resourceInfo['entryType'] = entryType;
          resourceInfo['ret']=ret;
          resourceMetric[GC.WORKER_START] = getFixedMetric(item, GC.WORKER_START);
          resourceMetric[GC.REDIRECT_START] = getFixedMetric(item, GC.REDIRECT_START);
          resourceMetric[GC.REDIRECT_END] = getFixedMetric(item, GC.REDIRECT_END);
          resourceMetric[GC.FETCH_START] = getFixedMetric(item, GC.FETCH_START);
          resourceMetric[GC.DOMAIN_LOOKUP_START] = getFixedMetric(item, GC.DOMAIN_LOOKUP_START);
          resourceMetric[GC.DOMAIN_LOOKUP_END] = getFixedMetric(item, GC.DOMAIN_LOOKUP_END);
          resourceMetric[GC.CONNECT_START] = getFixedMetric(item, GC.CONNECT_START);
          resourceMetric[GC.CONNECT_END] = getFixedMetric(item, GC.CONNECT_END);
          resourceMetric[GC.SECURE_CONNECTION_START] = getFixedMetric(item, GC.SECURE_CONNECTION_START);
          resourceMetric[GC.REQUEST_START] = getFixedMetric(item, GC.REQUEST_START);
          resourceMetric[GC.RESPONSE_START] = getFixedMetric(item, GC.RESPONSE_START);
          resourceMetric[GC.RESPONSE_END] = getFixedMetric(item, GC.RESPONSE_END);
          resourceMetric[GC.RESPONSE_STATUS]=item[GC.RESPONSE_STATUS];
          resourceInfo[GC.DURATION] = isDefined(item[GC.DURATION]) ? getFixedMetric(item, GC.DURATION)
            : (resourceMetric[GC.RESPONSE_END] - resourceMetric[GC.START_TIME]);
    
          if (isDefined(item[GC.DECODED_BODY_SIZE])) {
            resourceInfo[GC.NEXT_HOP_PROTOCOL] = item[GC.NEXT_HOP_PROTOCOL];
            resourceMetric[GC.TRANSFER_SIZE] = item[GC.TRANSFER_SIZE];
            resourceMetric[GC.ENCODED_BODY_SIZE] = item[GC.ENCODED_BODY_SIZE]>=Math.pow(2,64)?Math.pow(2,60):item[GC.ENCODED_BODY_SIZE];
            resourceMetric[GC.DECODED_BODY_SIZE] = item[GC.DECODED_BODY_SIZE];
          }
          return { info: resourceInfo, metric: resourceMetric }
        }
      });
      return datas
  }

  // 获取tti
  function getTTI(fcp,longTaskEntries){
      const basicTime = 5000; // 5s区间循环查询周期
        // startTime 循环查找开始时间，domContentLoadedEventStart减去navigationstart
        // longTaskEntries为performance.getEntriesByType('long-task')
        // resourceEntries为performance.getEntriesByType('resource')
        // domContentLoadedTime为domContentLoadedEventEnd
        function getTTITime(startTime,longTaskEntries, resourceEntries,domContentLoadedTime) {
          let busyNetworkInWindow = [];
          let tti = startTime;
          while (startTime + basicTime <= 50000) { //从前50s 中去找
              tti = startTime;
              // 在长线程列表里查找，返回小于开始+5s的时间，大于开始开始时间的数据
              var  longTasksInWindow = longTaskEntries.filter(task => {
                  return task.startTime < startTime + basicTime && task.startTime + task.duration > startTime;
              });
              // 如果数据存在
              if (longTasksInWindow.length) {
                  // 找到最后一条数据，开始时间变更为最后一条数据的截至时间，继续下一轮查找
                  const lastLongTask = longTasksInWindow[longTasksInWindow.length - 1];
                  startTime = lastLongTask.startTime + lastLongTask.duration;
                  continue;
              }
              // 查找网络请求 ，去掉网络请求大于开始时间+5s的和网络请求结束时间小于开始时间的
              busyNetworkInWindow = resourceEntries.filter(request => {
                  return !(request.startTime >= startTime + basicTime || request.startTime + request.duration <= startTime);
              });
              // 如果网络请求数据存在且数量大于2，变更开始时间为第一个网络请求的结束时间继续进行向后查找
              if (busyNetworkInWindow.length > 2) {
                  const firstRequest = busyNetworkInWindow[0];
                  startTime = firstRequest.startTime + firstRequest.duration;
                  continue;
              }
              // 返回 
              return Math.max(tti, domContentLoadedTime);
          }
          return Math.max(tti, domContentLoadedTime);
      }
      // var domContentLoadedEventStart=performance.timing&&performance.timing.domContentLoadedEventStart
      // var navigationstart=performance.timing.navigationStart
      var domContentLoadedTime=performance.timing.domContentLoadedEventEnd-performance.timing.domContentLoadedEventStart;
      var resourceEntries=performance.getEntriesByType('resource');
      // var startTime=domContentLoadedEventStart-navigationstart
      return  getTTITime(fcp,longTaskEntries,resourceEntries,domContentLoadedTime)
  }

  // 获取数据
  function getAllPageMetrics() {
      var screen = window.screen || {};
      var pageInfo = {
        timestamp: now(0),
        title: globalData.title,
        referrer: document.referrer,
        charset: document.characterSet || document.charset || '',
        embed: window.top && window.self && window.top !== window.self ? 1 : 0,
        width: screen.width || 0,
        height: screen.height || 0,
        completed: globalData.state,
        param:location&&location.search||''
      };
      var supported = window.performance && window.performance.timing;
      pageInfo.supported = isDefined(supported) ? 1 : 0;
      if (!supported) {
        log('C109');
        pageInfo[GC.DURATION] = tillNow();
        return { info: pageInfo }
      }
      var pageMetric = {};
      var timing = window.performance.timing;
      var start = timing[GC.NAVIGATION_START] || timing[GC.FETCH_START];
      pageMetric[GC.NAVIGATION_START] = start && start || '';
      pageMetric[GC.UNLOAD_EVENT_START] = getRelativePeriod(timing[GC.UNLOAD_EVENT_START], start);
      pageMetric[GC.UNLOAD_EVENT_END] = getRelativePeriod(timing[GC.UNLOAD_EVENT_END], start);
      pageMetric[GC.REDIRECT_START] = getRelativePeriod(timing[GC.REDIRECT_START], start);
      pageMetric[GC.REDIRECT_END] = getRelativePeriod(timing[GC.REDIRECT_END], start);
      pageMetric[GC.FETCH_START] = getRelativePeriod(timing[GC.FETCH_START], start);
      pageMetric[GC.DOMAIN_LOOKUP_START] = getRelativePeriod(timing[GC.DOMAIN_LOOKUP_START], start);
      pageMetric[GC.DOMAIN_LOOKUP_END] = getRelativePeriod(timing[GC.DOMAIN_LOOKUP_END], start);
      pageMetric[GC.CONNECT_START] = getRelativePeriod(timing[GC.CONNECT_START], start);
      pageMetric[GC.CONNECT_END] = getRelativePeriod(timing[GC.CONNECT_END], start);
      pageMetric[GC.SECURE_CONNECTION_START] = getRelativePeriod(timing[GC.SECURE_CONNECTION_START], start);
      pageMetric[GC.REQUEST_START] = getRelativePeriod(timing[GC.REQUEST_START], start);
      pageMetric[GC.RESPONSE_START] = getRelativePeriod(timing[GC.RESPONSE_START], start);
      pageMetric[GC.RESPONSE_END] = getRelativePeriod(timing[GC.RESPONSE_END], start);
      pageMetric[GC.DOM_LOADING] = getRelativePeriod(timing[GC.DOM_LOADING], start);
      pageMetric[GC.DOM_INTERACTIVE] = getRelativePeriod(timing[GC.DOM_INTERACTIVE], start);
      pageMetric[GC.DOM_CONTENT_LOADED_EVENT_START] = getRelativePeriod(timing[GC.DOM_CONTENT_LOADED_EVENT_START], start);
      pageMetric[GC.DOM_CONTENT_LOADED_EVENT_END] = getRelativePeriod(timing[GC.DOM_CONTENT_LOADED_EVENT_END], start);
      pageMetric[GC.DOM_COMPLETE] = getRelativePeriod(timing[GC.DOM_COMPLETE], start);
      pageMetric[GC.LOAD_EVENT_START] = getRelativePeriod(timing[GC.LOAD_EVENT_START], start);
      pageMetric[GC.LOAD_EVENT_END] = getRelativePeriod(timing[GC.LOAD_EVENT_END], start);
      pageMetric[GC.FULL_RESOURCE_LOAD_TIME] = getResourceLoadTime();
      pageInfo[GC.DURATION] = globalData.state ? Math.max(0, pageMetric[GC.LOAD_EVENT_END], pageMetric[GC.LOAD_EVENT_START]) : Math.round(tillNow()/1000);
      if (window.performance.getEntriesByType) {
        var navigationEntry = last(window.performance.getEntriesByType('navigation'));
        if (isDefined(navigationEntry)) {
          pageInfo.type = navigationEntry.type;
          pageInfo[GC.NEXT_HOP_PROTOCOL] = navigationEntry[GC.NEXT_HOP_PROTOCOL];
          pageMetric[GC.REDIRECT_COUNT] = navigationEntry[GC.REDIRECT_COUNT];
          pageMetric[GC.TRANSFER_SIZE] = navigationEntry[GC.TRANSFER_SIZE];
          pageMetric[GC.ENCODED_BODY_SIZE] = navigationEntry[GC.ENCODED_BODY_SIZE];
          pageMetric[GC.DECODED_BODY_SIZE] = navigationEntry[GC.DECODED_BODY_SIZE];
          pageMetric[GC.RESPONSE_STATUS]=navigationEntry[GC.RESPONSE_STATUS];
        }
      }
      let paintData=getPaintMetrics();
      extend(pageMetric, paintData);
      if(paintData&&paintData.fcp){
        let fcp=paintData.fcp;
        let tti=getTTI(fcp,longTaskEntries)||0;
        extend(pageMetric,{'tti':Math.round(tti)});
      }
      return { info: pageInfo, metric: pageMetric }
  }


  //  获取langtask
  function getlongtask(){
      try{
        var observer = new PerformanceObserver(function (list) {
          longTaskEntries = list.getEntries();
        });
        observer.observe({ entryTypes: ["longtask"] });
      }catch(e){
          log("C115");
      }
      return longTaskEntries
  }
  /**
   * @descripe 浏览器资源时间性能缓冲满了会自动清理，在清理的过程中对数据进行缓存
   **/
  function listenForDumpResources() {
    if (window.performance && window.performance.getEntriesByType) {
      var getCallback = function (e) {
        return function () {
          log('Dump when resource buffer is full');
          var entries = window.performance.getEntriesByType('resource');
          notifierEmit({ t: GC.RESOURCE_DUMP, p: entries });

          if (!synced) {
            resources = resources.concat(entries);
          }
          var clearMethod = e + 'learResourceTimings';
          if (clearMethod in window.performance) {
            window.performance[clearMethod]();
          }
        }
      };

      // 当浏览器的资源时间性能缓冲区已满时会触发resourcetimingbufferfull
      addListener(window.performance, 'resourcetimingbufferfull', getCallback('c'), false);
      addListener(window.performance, 'webkitresourcetimingbufferfull', getCallback('webkitC'), false);
    }
  }
  function initDocumentCollector() {
      notifierOn(GC.LIFESTYLE_XHR_START,function(evt){
        /*给触发的请求关联上onload期间发起的标识*/
        if(isDefined(evt.info)){
          evt.info.isRelatedH5=true;
        }
        requestCount=requestCount+1;
      });
      notifierOn(GC.LIFESTYLE_FETCH_START,function(evt){
        /*给触发的请求关联上onload期间发起的标识*/
        if(isDefined(evt.info)){
          evt.info.isRelatedH5=true;
        }
        requestCount=requestCount+1;
      });
      notifierOn(GC.LIFESTYLE_REQUEST_END+"H5",function(evt){
        requestCount=requestCount-1;
        let settRequestEvent=requestService(JSON.parse(JSON.stringify(evt.requestData)),GS.sett,true);
        h5RelatedEvents.push({k:settRequestEvent.type,ent:settRequestEvent.ent,sin:settRequestEvent.sin,v:settRequestEvent.data});
        if(!isEmpty(GS.secondSett)){
          if(checkMoudle('network')){
            let settSecondRequestEvent=requestService(JSON.parse(JSON.stringify(evt.requestData)),GS.secondSett,true);
            h5RelatedEventsSecond.push({k:settSecondRequestEvent.type,ent:settSecondRequestEvent.ent,sin:settSecondRequestEvent.sin,v:settSecondRequestEvent.data});
          }
        }
        /*onload之前发起的网络回调完毕*/
        if(requestCount===0){
          notifierRemove(GC.LIFESTYLE_XHR_START);
          notifierRemove(GC.LIFESTYLE_FETCH_START);
          notifierRemove(GC.LIFESTYLE_REQUEST_END+"H5");
          notifierEmit({ t: GC.RESOURCE_DATA,p:{},type:3,revts:h5RelatedEvents});
          /*后置配置生成revts*/
          if(!isEmpty(GS.secondSett)){
            notifierEmit({ t: GC.RESOURCE_DATA,p:{},type:4,revts:h5RelatedEventsSecond});
          }
        }
      });
      addListener(document, 'DOMContentLoaded', function () {
          notifierEmit({ t: GC.PAGE_READY });
      });
      /*注入时机较晚页面已完成了加载*/
      if (document.readyState === 'complete' && !synced) {
        if (!startWith(document.location.href, 'about:') || !startWith(document.URL, 'about:')) {
          onload.call();
          specialCollect=true;
        }
      } else {
        on$1(window,'load',onload);
      }
      /*关闭页面或者跳转页面,清空缓存数据队列,避免队列数据未上报*/
      on$1(window, 'pagehide', function () {
        flushData(true);
      }, false);
      listenForPaintMetrics();
      listenForDumpResources();
  }

  var deamonEntries = [];
    var deamonStart;
    var requestInQueue = [];
    var types = [GC.XML_HTTP_REQUEST, GC.FETCH];
    var sortCond = function (a, b) {
      return a[GC.START_TIME] - b[GC.START_TIME]
    };
    function getCookieUserID(){
      let cookieArr=getUserIdManageClass.cookieArr;
      let configeManage=getUserIdManageClass.configeManage;
      if(cookieArr.length>0){
        for(let i=0,j=cookieArr.length-1;i<=j;i++){
          let da=getCookie(cookieArr[i].rule);
          if(isDefined(da)&&checkValue(da)){
            if(cookieArr[i].index<=getUserIdManageClass.isStopGetValue){
              configeManage[cookieArr[i].index]["value"]=""+da;
              getUserIdManageClass.checkValueRight();
              return
            }
          }
        }
      }
    }
    
    
    
    // 获取请求历史记录中当前请求的条目，其中做了去除不同类型的条目，还有根据发生时间排序和去重
    function filterEntry(requestInfo) {
      var url = requestInfo.url;
      var stamp = requestInfo[GC.TIMESTAMP];
      var type = types[requestInfo.type];
      var matchedEnt;
      // 过滤数据xhr且同url的请求的请求
      var inqueue = map(requestInQueue, function (info) {
        if (info.url === url && types[info.type] === type) {
          return info
        }
      });
      inqueue.sort(sortCond);
      var index = -1;
      // 判断是否有同一时间发送到额请求，有就return
      forEach(inqueue, function (ret, i) {
        if (ret[GC.TIMESTAMP] === stamp) {
          index = i;
          return false
        }
      });
      if (index < 0) {
        log('C130');
        return matchedEnt
      }
      // 判断相同的请求
      var allEntries = map(deamonEntries, function (r, i) {
        if (match(r, url, type)) {
          return r
        }
      });
      // 如果当前请求不在已经统计了的请求中，就在已经发送的请求数组中追加新的请求
      if (index >= allEntries.length) {
        log('C131');
        var fromResource = [];
        if (window.performance.getEntriesByType) {
          fromResource = map(window.performance.getEntriesByType('resource'), function (ent) {
            if (match(ent, url, type)) {
              return ent
            }
          });
        }
        allEntries = allEntries.concat(fromResource);
      } else {
        log('C132');
      }
      // 根据发生时间排序
      allEntries.sort(sortCond);
      if (allEntries.length < 1 || index >= allEntries.length) {
        log('C133');
        return matchedEnt
      }
      // 返回对应的条目
      return allEntries[index]
    }
    function inWatchingRequest(ent) {
      return (ent.initiatorType === GC.XML_HTTP_REQUEST || ent.initiatorType === GC.FETCH) && (ent[GC.START_TIME] > deamonStart)
    }
    function match(ent, url, type) {
      return inWatchingRequest(ent) && endWith(ent.name, url) && ent.initiatorType === type
    }
    function isFullyResponsed(status) {
      return status > 0 && status < 600
    } 
    var extendMetrics = function (req) {
      if (!window.performance || !window.performance.now) {
        log('C134');
        return req
      }
      var requestInfo = req.info;
      var status = requestInfo.status || requestInfo.code;
      if (!isFullyResponsed(status)) {
        log('C135');
        return req
      }
      // 获取相同的历史请求条目
      var relatedEntry = filterEntry(requestInfo);
      // if (isSurelyMatch(relatedEntry, requestInfo)) {
        // if (isUnaccessibleCrosRequest(relatedEntry)) {
        //   log('C136')
        //   return req
        // }
      if (isDefined(relatedEntry)) {
        var requestMetric = req.metric;
        // 重设START_TIME/TIMESTAMP/DURATION
        requestInfo[GC.START_TIME] = getFixedMetric(relatedEntry, GC.START_TIME) * 1000;
        requestInfo[GC.TIMESTAMP] = (requestInfo[GC.START_TIME]/1000 + window.performance.timing.navigationStart)*1000;
        requestInfo[GC.DURATION] = getFixedMetric(relatedEntry, GC.DURATION) * 1000;
        requestMetric[GC.REDIRECT_START] = getFixedMetric(relatedEntry, GC.REDIRECT_START) * 1000;
        requestMetric[GC.REDIRECT_END] = getFixedMetric(relatedEntry, GC.REDIRECT_END) * 1000;
        requestMetric[GC.FETCH_START] = getFixedMetric(relatedEntry, GC.FETCH_START) * 1000;
        requestMetric[GC.DOMAIN_LOOKUP_START] = getFixedMetric(relatedEntry, GC.DOMAIN_LOOKUP_START) * 1000;
        requestMetric[GC.DOMAIN_LOOKUP_END] = getFixedMetric(relatedEntry, GC.DOMAIN_LOOKUP_END) * 1000;
        requestMetric[GC.CONNECT_START] = getFixedMetric(relatedEntry, GC.CONNECT_START) * 1000;
        requestMetric[GC.CONNECT_END] = getFixedMetric(relatedEntry, GC.CONNECT_END) * 1000;
        requestMetric[GC.SECURE_CONNECTION_START] = getFixedMetric(relatedEntry, GC.SECURE_CONNECTION_START) * 1000;
        requestMetric[GC.RESPONSE_START] = getFixedMetric(relatedEntry, GC.RESPONSE_START) * 1000;
        requestMetric[GC.REQUEST_START] =getFixedMetric(relatedEntry, GC.REQUEST_START) * 1000;
        requestMetric[GC.RESPONSE_END] = getFixedMetric(relatedEntry, GC.RESPONSE_END) * 1000;
        if (isDefined(relatedEntry[GC.DECODED_BODY_SIZE])) {
          requestInfo[GC.NEXT_HOP_PROTOCOL] = relatedEntry[GC.NEXT_HOP_PROTOCOL];
          requestMetric[GC.WORKER_START] = getFixedMetric(relatedEntry, GC.WORKER_START) * 1000;
          requestMetric[GC.TRANSFER_SIZE] = getFixedMetric(relatedEntry, GC.TRANSFER_SIZE);
          requestMetric[GC.ENCODED_BODY_SIZE] = getFixedMetric(relatedEntry, GC.ENCODED_BODY_SIZE);
          requestMetric[GC.DECODED_BODY_SIZE] = getFixedMetric(relatedEntry, GC.DECODED_BODY_SIZE);
        }
      } else {
        log('C137');
      }
      return req
    };
    var polyfillMetric = function (metric) {
      var requestInfo = metric.info;
      var requestMetric = metric.metric;
      // 请求发起到响应结束的时间
      if (!isDefined(requestInfo[GC.DURATION])) {
        requestInfo[GC.DURATION] = requestMetric[GC.RESPONSE_END] - requestInfo[GC.START_TIME];
      }
      // 不存在callbackerror则赋值0
      if (!isDefined(requestInfo.callbackError)) {
        requestInfo.callbackError = 0;
      }
      return metric
    };
    // 将当前这条请求添加到请求队列
    var queueRequest = function (req) {
      var requestInfo = req.info;
      var status = requestInfo.status||requestInfo.code;
      if (isFullyResponsed(status)) {
        requestInQueue.push(req.info);
      }
    };
    function initDeamon() {
      deamonStart = tillNow()/1000||0;
      notifierOn(GC.RESOURCE_DUMP, function (evt) {
        var entries = evt.p;
        var requestEntries = map(entries, function (ent) {
          if (inWatchingRequest(ent)) {
            return ent
          }
        });
        deamonEntries = deamonEntries.concat(requestEntries);
      });
    }
   
    // 黑白名单
    class blackAndWhite {
      constructor(){
        this.list={};
        this.isOpen=false,
        this.blackKey=[];
      }
      // 检查是否开启黑白名单
      checkIsOpen(){
        if(isDefined(GS.sett.brss)&&!GS.sett.brss){
          this.isOpen=false;
          return 
        }
        if(isDefined(GS.secondSett.brss)&&!GS.secondSett.brss){
          this.isOpen=false;
          return 
        }
        this.isOpen=true;
      }
      // 获取当前url对应黑白名单信息，如果有直接取出来，没有就过滤一条然后返回
      getItem(url,pathname,type){
        let saveUrl=`${url}+${pathname}`;
        if(isDefined(url)&&this.list[saveUrl]){
          //存在
          return this.list[saveUrl]
        }else {
          return  this.setItem(url,pathname,type)
        }
      }
      setItem(url,pathname,type){
        let {urlTotalList,urlWhiteList,urlBlackList}=isDefined(GS.sett.traceConfig)?GS.sett.traceConfig:{urlTotalList:[],urlBlackList:[],urlWhiteList:[]};
        /*合并黑白名单配置*/
        if(isDefined(GS.secondSett.traceConfig)){
          if(isDefined(GS.secondSett.traceConfig.urlTotalList)){
            if(isDefined(urlTotalList)){
              urlTotalList=urlTotalList.concat(GS.secondSett.traceConfig.urlTotalList);
            }else {
              urlTotalList=GS.secondSett.traceConfig.urlTotalList;
            }  
          }
          if(isDefined(GS.secondSett.traceConfig.urlWhiteList)){
            if(isDefined(urlWhiteList)){
              urlWhiteList=urlWhiteList.concat(GS.secondSett.traceConfig.urlWhiteList);
            }else {
              urlWhiteList=GS.secondSett.traceConfig.urlWhiteList;
            } 
          }
          if(isDefined(GS.secondSett.traceConfig.urlBlackList)){
            if(isDefined(urlBlackList)){
              urlBlackList=urlBlackList.concat(GS.secondSett.traceConfig.urlBlackList);
            }else {
              urlBlackList=GS.secondSett.traceConfig.urlBlackList;
            }
          }
        }
        let obj={};
        if(isDefined(urlTotalList)&&urlTotalList.length>0){
          if(urlTotalList.length>200){
            urlTotalList=urlTotalList.slice(0,200);
          }
          for(let i=0,j=urlTotalList.length-1;i<=j;i++){
            extend(obj,this.totalHead(urlTotalList[i],url,pathname,type)); 
          }
        }
        if(isDefined(urlWhiteList)&&urlWhiteList.length>0){
          if(urlWhiteList.length>200){
            urlWhiteList=urlWhiteList.slice(0,200);
          }
          for(let a=0,b=urlWhiteList.length-1;a<=b;a++){
            if(this.whiteCheck(url,urlWhiteList[a])){
              extend(obj,this.whiteHead(urlWhiteList[a],url,pathname,type));
            }
          }
        }
        if(isDefined(urlBlackList)&&urlBlackList.length>0){
          if(urlBlackList.length>200){
            urlBlackList=urlBlackList.slice(0,200);
          }
          for(let m=0,n=urlBlackList.length-1;m<=n;m++){
            if(this.black(url,urlBlackList[m])){
              extend(obj,this.blackHead(urlBlackList[m],url,pathname,type));
            }else {
              this.getBlackKey(urlBlackList[m]);
            }
          }
        }
        if(Object.keys(obj).length>200){
          obj=getElementForNum(obj,200);
        }
        obj=this.delBlackKey(obj);
        let saveUrl=`${url}+${pathname}`;
        this.list[saveUrl]=obj;
        return obj;
      }
      delBlackKey(obj){
        if(this.blackKey.length>0){
          for(let i=0,j=this.blackKey.length-1;i<=j;i++){
            if(isDefined(obj[this.blackKey[i]])){
              delete obj[this.blackKey[i]];
            }
          }
        }
        this.blackKey=[];
        return obj
      }
      getBlackKey(hr) {
        const reqHeaderRules = hr && hr["reqHeaderRules"];
        if (isDefined(reqHeaderRules) && reqHeaderRules.length > 0 && this.blackKey) {
          for (let i = 0, j = reqHeaderRules.length - 1; i <= j; i++) {
            if (reqHeaderRules[i] && reqHeaderRules[i]['key']) {
              this.blackKey.push(reqHeaderRules[i]['key']);
            }
          }
        }
      }
    
      totalHead(hr,url,pathname,type){
        let obj={};
        extend(obj,this.constructData(hr,url,pathname,type));
        return obj
      }
      whiteCheck(url,hr){
        if(hr["reqHeaderRules"]&&hr["reqHeaderRules"].length>0){
          if(includes([0,1,2,3,4],hr["type"])===false){
            return false
          }
          switch(hr["type"]){
            case 0:
              if(url==hr["rule"]){
                return true
              }
              break;
            case 1:
              if(startWith(url,hr["rule"])){
                return true
              }
              break;
            case 2:
              if(endWith(url,hr["rule"])){
                return true
              }
              break;
            case 3:
              let reg=new RegExp(hr["rule"]);
              if(reg instanceof RegExp && reg.test(url)){
                return true
              }
              break;
            case 4:
              if(url.indexOf(hr["rule"])>-1){
                return true
              }
              break;
            default:
              return false;
          }
        }
        return false
      }
      whiteHead(hr,url,pathname,type){
        let reqHeaderRules=hr["reqHeaderRules"];
        let obj={};
        if(isDefined(reqHeaderRules)&&reqHeaderRules.length>0){
          for(let i=0,j=reqHeaderRules.length-1;i<=j;i++){
            extend(obj,this.constructData(reqHeaderRules[i],url,pathname,type));
          }
        }
        return obj
      }
      black(url,hr){
        if(hr["reqHeaderRules"]&&hr["reqHeaderRules"].length>0){
          if(includes([0,1,2,3,4],hr["type"])===false){
            return false
          }
          switch(hr["type"]){
            case 0:
              if(url==hr["rule"]){
                return false
              }
              break;
            case 1:
              if(startWith(url,hr["rule"])){
                return false
              }
              break;
            case 2:
              if(endWith(url,hr["rule"])){
                return false
              }
              break;
            case 3:
              let reg=new RegExp(hr["rule"]);
              if(reg instanceof RegExp && reg.test(url)){
                return false
              }
              break;
            case 4:
              if(url.indexOf(hr["rule"])>-1){
                return false
              }
              break;
            default:
              return true;
          }
        }
        return true
      }
      blackHead(hr,url,pathname,type){
        let reqHeaderRules=hr["reqHeaderRules"];
        let obj={};
        if(isDefined(reqHeaderRules)&&reqHeaderRules.length>0){
          for(let i=0,j=reqHeaderRules.length-1;i<=j;i++){
            extend(obj,this.constructData(reqHeaderRules[i],url,pathname,type));
          }
        }
        return obj
      }
      checkKey(key,num,type){
        if(type&&type!==1){
          return true
        }
        if(!isDefined(key)){
          return false
        }
        if(key.length>num){
          return false
        }
        if (num === 256) {
          if(/^[0-9a-zA-Z_-]{1,256}$/.test(key)){return true}
          return false
        }
        if(trim(key)==""){
          return false
        }
        return true
      }
      constructData(reqHeaderRules,url,pathname,requestType){
        let obj={};
        let useAgent=getUserAgent();
        let type=useAgent&&(useAgent.osName+"/"+useAgent.osVersion)||GS.sett.osType&&GS.sett.typeArr[GS.sett.osType]||GS.sett.typeArr[1];
        if(isDefined(reqHeaderRules)&&isDefined(reqHeaderRules["type"])&&this.checkKey(reqHeaderRules["key"],256)){
          if(isDefined(reqHeaderRules["value"])&&this.checkKey(reqHeaderRules["value"],512)===false){
            return
          }
          switch(reqHeaderRules["type"]){
            case 1:
              if(isDefined(reqHeaderRules["value"])){
                obj[reqHeaderRules["key"]]=reqHeaderRules["value"];
              }
              break;
            case 2:
              obj[reqHeaderRules["key"]]={fun:uuidWithLength, len:16,sky:false};
              break;
            case 3:
              obj[reqHeaderRules["key"]]={fun:uuidWithLength,len:32,sky:false};
              break;
            case 4:
              obj[reqHeaderRules["key"]]={fun:skyData, len:32,sky:true,url:url,pathname:pathname };
              break;
            case 5:
              obj[reqHeaderRules["key"]]={fun:traceId, len:32,sky:false};
              break;
            case 6:
              obj[reqHeaderRules["key"]]="bnro="+type+"_js/"+GS.sett.agentVersion; //_fetch
              break;
          }
        }
        return obj
      }
    }
    let  BWexample=new blackAndWhite();
    
    function checkBlackAndWhite(info,type){
      if(isDefined(info.url)){
       let getLocation=function(href) {
        if(href.indexOf("http")===0){
            var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);
            return match && {
                href: href,
                protocol: match[1],
                host: match[2],
                hostname: match[3],
                port: match[4],
                pathname: match[5],
                search: match[6],
                hash: match[7]
            }
        }else {
            var match = href.match(/^(file?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);
            return match && {
                href: href,
                protocol: match[1],
                host: match[2],
                hostname: match[3],
                port: match[4],
                pathname: match[5],
                search: match[6],
                hash: match[7]
            }
        }
    };
       let url=getLocation(info.url);
       if(!isDefined(url)){
          return undefined
       }
       let host=isDefined(url.hostname)?url.hostname:"";
       let pathname=isDefined(url.pathname)?url.pathname:"";
       if(isDefined(host)){
         return BWexample.getItem(host,pathname,type)
       }
      }
      return undefined
     }
    function skyData(url,pathname){
      let traceIdStr =String(enBase64(skyUuid()));
      let segmentId = String(enBase64(skyUuid()));
      let appName = String(enBase64(GS.sett.appName));
      let version = String(enBase64(GS.sett.appVersion));
      let path = pathname&&String(enBase64(pathname))||String(enBase64("/"));
      let host = String(enBase64(url));
      return `1-${traceIdStr}-${segmentId}-0-${appName}-${version}-${path}-${host}`
    }

  var callbackXhrIdentify$1={isPeriod:false,actionID:'',networkID:''};
    /**
     * @descripe 对挂载的数据metric进行初步时间设置
     * @param {object} ins xhr实例
     * @param {*} index key
     **/
    function safetySetMetric (ins, index, mandatory) {
      if (ins.$metric) {
        var requestMetric = ins.$metric.metric;
        if (!isDefined(requestMetric[index]) || mandatory) {
          requestMetric[index] = tillNow();
        }
      }
    }
    /**
     * @descripe 对挂载的数据info进行设置
     * @param {object} ins xhr实例
     * @param {*} index key
     **/
    function safetySetInfo (ins, index, val) {
      if (ins.$metric) {
        var requestInfo = ins.$metric.info;
        requestInfo[index] = val;
      }
    }
    
      /**
     * @descripe 获取安全的报错信息,非服务异常报错
     **/
    function safetySetErrorInfo (ins, index, val, eType,message) {
      if (ins.$metric) {
        var requestInfo = ins.$metric.info;
        requestInfo[index] = val;
        requestInfo[GC.MESSAGE] = message;
        requestInfo[GC.E_TYPE] = eType;
      }
    }
    
    
    
    
    /** 
     * @descripe hook从open参数获取基础信息
     * @param {*} method 
     * @param {*} path 
     * 客户问题：广汽丰田用到location当作url的情况，罕见但是遇到了，也不是不可以兼容，同时兼容xhr和fetch
    **/
    function beforeXHROpen(method, path) {
        /*对于path是非标准参数时不做处理*/
        let _path=path;
        if(typeof path !=='string'){
            _path=path.href||'';
        }
        _path = getUrl$1(_path);
        let ipPort = getIP(_path);
        if (this.$$inner) {
          return
        }
        this.$metric = {
          info: {
            id:uuid(),
            url: _path.slice(0,4096),
            ip: ipPort[0]||'',
            port:ipPort[1]||'',
            method: toUpper(method),
            type: 0,
            protocalType: _path.indexOf('https')>-1 ? 2 : 1,
            reqUrlDta:isDefined(GS.sett.reqURLKey || GS.secondSett.reqURLKey) && getParams(_path)||'',
            reqhtData:{},
            reshtData:{}
          }
        };
        if(isDefined(GS.sett)&&isDefined(GS.sett.pageViewId)){
          this.$metric.info['pageViewId']=GS.sett.pageViewId;
        }
    }
    /** 
     * @descripe 路径中获取路径参数
     * @param {*} path 
    **/
    function getParams(path) {
      if ( !isDefined(path)) { return '' }
      return  String.prototype.split.call(path,'?')[1]
    }
    
     /** 
     * @descripe 请求结束1:从performance缓存中匹配更新数据指标;2:响应体数据大小;3:resht业务处理;4:响应头获取;5:响应头与用户ID的处理;
     * @param {*} endTime 请求结束时刻 
     **/
    function XHREnd (endTime) {
      if (!this.$metric) {
        return
      }
    
      if (this.$$done) {
        return
      }
      this.$$done = true;
    
      var metric = this.$metric;
      var requestInfo = metric.info;
      var requestMetric = metric.metric;
      extendMetrics(metric); // 更新metric数据
      polyfillMetric(metric);  // 更新info时间
      /* in some bugly browsers, any attempt to get status on failed request will ends up an exception. */
      try {
        //requestInfo.message = this.statusText   // 
        if (!isDefined(requestMetric[GC.DECODED_BODY_SIZE]) || requestMetric[GC.DECODED_BODY_SIZE] <= 0) {
          var contentSize;
          if (this.responseType === '' || this.responseType === 'text') {
            contentSize = getContentSize(this.responseText);
          } else {
            contentSize = getContentSize(this.response);
          }
          requestMetric[GC.DECODED_BODY_SIZE] = contentSize;
        }
    
        if (this.getAllResponseHeaders) {
          var oriArr= this.getAllResponseHeaders();
          var allHeaders =oriArr;
          var allHeadersStr=toLower(allHeaders);
          var arr = allHeaders.trim().split(/[\r\n]+/);
          var headerMap = {};
          arr.forEach(function (line) {
            var parts = line.split(': ');
            var header = parts.shift();
            var value = parts.join(': ');
            headerMap[header] = value;
          });
          // requestInfo.guid = allHeadersStr.indexOf(GC.GUID_KEY) > -1 ? headerMap[GC.GUID_KEY].split(',')[0] : '';
          // requestInfo.xBrResponse = allHeadersStr.indexOf(GC.X_BR_RESPONSE) > -1 ? headerMap[GC.X_BR_RESPONSE].split(',')[0] : '';
          // requestInfo.traceResponse = allHeadersStr.indexOf(GC.TRACE_RESPONSE) > -1 ? headerMap[GC.TRACE_RESPONSE].split(',')[0] : ''; 
          requestInfo.guid = isDefined(headerMap[GC.GUID_KEY]) && headerMap[GC.GUID_KEY].split(',')[0] || '';
          requestInfo.xBrResponse = isDefined(headerMap[GC.X_BR_RESPONSE]) && headerMap[GC.X_BR_RESPONSE].split(',')[0] || '';
          requestInfo.traceResponse = isDefined(headerMap[GC.TRACE_RESPONSE]) && headerMap[GC.TRACE_RESPONSE].split(',')[0] || ''; 
          requestInfo[GC.RESPONSE_HEADER] = withLength(allHeaders, 2000);
          var respHeaderTraceKeys=[];
          if(isDefined(GS.sett.respHeaderTraceKey)&&GS.sett.respHeaderTraceKey.length>0 || isDefined(GS.secondSett.respHeaderTraceKey)&&GS.secondSett.respHeaderTraceKey.length>0){
            /*合并配置,先将匹配的匹配上*/
            if(isDefined(GS.secondSett.respHeaderTraceKey)&&GS.secondSett.respHeaderTraceKey.length>0){
              if(isDefined(GS.sett.respHeaderTraceKey)){
                respHeaderTraceKeys=GS.sett.respHeaderTraceKey.concat(GS.secondSett.respHeaderTraceKey);
              }else {
                respHeaderTraceKeys=GS.secondSett.respHeaderTraceKey;
              } 
            }else {
              if(isDefined(GS.sett.respHeaderTraceKey)){
                respHeaderTraceKeys=GS.sett.respHeaderTraceKey;
              }
            }
            for(let i=0,j=respHeaderTraceKeys.length-1;i<=j;i++){
               if(allHeadersStr.indexOf(toLower(respHeaderTraceKeys[i])) > -1){
                requestInfo['reshtData'][respHeaderTraceKeys[i]]=this.getResponseHeader(respHeaderTraceKeys[i]);
               }
            }
          }
          getResponseHead(oriArr);
        }
      } catch (se) {
        log('C123');
      }
      notifierEmit({ t: GC.REQUEST_DATA, p: metric ,isRelatedH5:isDefined(metric.info.isRelatedH5)?true:false});
      setTimeout(function(){getCookieUserID();},50);
    }
    
    /** 
     * @descripe 响应头与用户ID的处理
     * @param {*} head 响应头数组
     **/
    function getResponseHead(head){
      head=head.trim();
      if(head.length>0){
        let headers=head.split(/[\r\n]+/);
        let headerMap = {};
        headers.forEach(function (line) {
          var parts = line.split(': ');
          var header = parts.shift();
          var value = parts.join(': ');
          headerMap[header] = value;
        });
        let responseArr=getUserIdManageClass.responseArr;
        let configeManage=getUserIdManageClass.configeManage;
        if(responseArr.length>0){
          for(let i=0,j=responseArr.length-1;i<=j;i++){
            let da=responseArr[i].rule.toLowerCase();
            if(headerMap.hasOwnProperty(da)){
              if(responseArr[i].index<=getUserIdManageClass.isStopGetValue){
                if(checkValue(headerMap[da])){
                  configeManage[responseArr[i].index]["value"]=""+headerMap[da];
                  getUserIdManageClass.checkValueRight();
                  return
                }
              }
            }
          }
        }
      }
    }
    
    
     
    /** 
     * @descripe 检测onreadystatechange是否被hack
     * @param {*} ins xhr对象
     **/
    function isHacked (ins) {
      return isFunction(prop(ins.onreadystatechange, '$$original'))
    }
    /** 
     * @descripe 检测xhr是否已完成
     * @param {*} ins xhr对象
     **/
    function isXHRDone (ins) {
      return ins.readyState === 0 || ins.readyState === 4
    }
     
    /** 
     * @descripe xhr的readystatechange事件回调
     **/
    function readystatechange () {
      beforestatechange.call(this);
    
      if (!isHacked(this)) {
        if (isXHRDone(this)) {
          afterstatechange.call(this);
        } else {
          this.onreadystatechange = hack(this.onreadystatechange, beforestatechange, afterstatechange, callbackError);
        }
      }
    }
      
    /**
    * @descripe readystatechange在回调前先获取一部分响应指标值
    **/
    function beforestatechange() {
      /*检测是否是关联操作网络的回调*/
      if(isDefined(this.$metric)&&isDefined(this.$metric.info)&&isDefined(this.$metric.info.ai)){
          /*beforestatechange可能会调用两次*/
          if(!callbackXhrIdentify$1.isPeriod&&callbackXhrIdentify$1.networkID!==this.$metric.info.id){
            callbackXhrIdentify$1.isPeriod=true;
            callbackXhrIdentify$1.actionID=this.$metric.info.ai;
            callbackXhrIdentify$1.networkID=this.$metric.info.id;
            notifierEmit({t:GC.XHR_CALLBACK_IDENTIFY,info:callbackXhrIdentify$1});
          }
      }
      if (this.readyState === 2) {
        safetySetMetric(this, GC.RESPONSE_START);
      }
    
      if (isXHRDone(this)) {
        safetySetMetric(this, GC.RESPONSE_START);
        safetySetMetric(this, GC.RESPONSE_END);
        safetySetMetric(this, GC.CALLBACK_START);
      }
    }
      
    /**
    * @descripe readystatechange在回调后执行1:获取状态码;2:更新指标数据;
    **/
    function afterstatechange () {
      if (isXHRDone(this)) {
        callbackXhrIdentify$1.isPeriod=false;
        notifierEmit({t:GC.XHR_CALLBACK_IDENTIFY,info:callbackXhrIdentify$1});
        let endTime=now();
        safetySetMetric(this, GC.CALLBACK_END);   // 获取callback结束时间
        var that = this;
        if (this.$metric) {
          var status = 0;
          try {
            status = this.status;
            this.$metric.info[GC.E_TYPE] = 'http';
          } catch (se) {
            log('C124');
            
          }
          if(status === 0){
            this.$metric.info[GC.E_TYPE] = 'XHR';
            this.$metric.info[GC.MESSAGE] = 'XHR internal services not available or Cross domain request';
          }
          this.$metric.info.code = status;
          queueRequest(this.$metric);
          delay(function () {
            log('C125');
            XHREnd.call(that,endTime);
          });
        }
      }
    }
    /**
    * @descripe readystatechange在hook还原执行过程中异常处理,异常赋值1,正常0
    **/
    function callbackError () {
      log('C126');
      var errorInfo = last(args(arguments));
      error(errorInfo);
      safetySetInfo(this, 'callbackError', 1);
    }
     
     /**
     * @descripe reqht业务处理
     * @param {object} key 请求头key
     * @param {object} val 请求头value
     * @param {object} metric 挂载的最终数据
     **/
    function getReqhead(key,val,metric){
      if(isDefined(GS.sett.reqHeaderTraceKey) || isDefined(GS.secondSett.reqHeaderTraceKey)){
        var reqHeaderTraceKeys=[];
        if(isDefined(GS.secondSett.reqHeaderTraceKey)&&GS.secondSett.reqHeaderTraceKey.length>0){
          if(isDefined(GS.sett.reqHeaderTraceKey)){
            reqHeaderTraceKeys=GS.sett.reqHeaderTraceKey.concat(GS.secondSett.reqHeaderTraceKey);
          }else {
            reqHeaderTraceKeys=GS.secondSett.reqHeaderTraceKey;
          }
        }else {
          if(isDefined(GS.sett.reqHeaderTraceKey)){
            reqHeaderTraceKeys=GS.sett.reqHeaderTraceKey;
          }
        }
        if(isDefined(reqHeaderTraceKeys)&&includes(reqHeaderTraceKeys.map(function(value){return value.toLowerCase()}),key.toLowerCase())){
          metric.info["reqhtData"][key]=val;
        }
    }
    }

    /**
     * @descripe 1:send前黑白名单处理;2readystatechange状态处理;3:添加请求异常监听
     * @param {object} content send参数
     **/
    function beforeXHRSend(content) {
        /*没有挂载$metric不做send前处理*/
        if (this.$$inner || !isDefined(this.$metric)) {
          return
        }
        /*发送前检查是否是在xhr回调期间*/
        if(callbackXhrIdentify$1.isPeriod){
            this.$metric.info.ai=callbackXhrIdentify$1.actionID;
            this.$metric.info.parentNetworkID=callbackXhrIdentify$1.networkID;
            notifierEmit({t:GC.LIFESTYLE_CALLBACK_REQUEST_START+this.$metric.info.ai});
        }
        notifierEmit({t:GC.LIFESTYLE_XHR_START,info:isDefined(this.$metric.info)?this.$metric.info:null});

        var that = this;
        /*检测是否开启brss*/
        BWexample.checkIsOpen();
        if(isDefined(this.$metric.info)&&BWexample.isOpen){
          /*精准ent*/
          this.$metric.info['timestamp']=now();
          let obj=checkBlackAndWhite(this.$metric.info,"_xhr");
          if(isDefined(obj)&&isObj(obj)){
            forEachOwn(obj,function(val,key){
              if(isObj(val)){
                let data;
                if(val.sky){
                  data=val.fun(val.url,val.pathname);
                }else {
                  data=val.fun(val.len);
                }
                that.setRequestHeader(key,data);
                getReqhead(key,data,that.$metric);
              }else {
                if(startWith(val,"bnro=")){
                  val+="_xhr_XMLHttpRequest";
                }
                that.setRequestHeader(key,val);
                getReqhead(key,val,that.$metric);
              }
            });
          }
        }
        if (isFunction(this.addEventListener)) {
          forEach(['abort', 'timeout', 'error'], function (e, i) {
            var message = ['User terminates XHR request','XHR request timeout','XHR request exception'];
            addListener(that, e, function () {
                safetySetErrorInfo(that, 'code', 600 + Number(i),'XHR',message[i]);
            }, false);
          });
          addListener(this, 'readystatechange', readystatechange, false);
        } else {
          var checkTimes = 3;
          var checkOnreadystatechangeHook = function () {
            delay(function () {
              if (isXHRDone(that) && !isHacked(that)) {
                return afterstatechange.call(that)
              }
      
              if (!isXHRDone(that)) {
                that.onreadystatechange = hack(that.onreadystatechange, beforestatechange, afterstatechange, callbackError);
                if (--checkTimes >= 0) {
                  checkOnreadystatechangeHook();
                }
              }
            });
          };
          checkOnreadystatechangeHook();
        }
        this.onreadystatechange = hack(this.onreadystatechange, beforestatechange, afterstatechange, callbackError);
      
        var requestInfo = this.$metric.info;
        extend(requestInfo, getTime());
        
        var requestMetric = this.$metric.metric = {};
        try {
          requestInfo[GC.REQUEST_BODY] = getRequestParam(content);
          requestMetric[GC.UPLOAD_BODY_SIZE] = getContentSize(content);
        } catch (se) {
          log('C127');
        }
    }
    /**
     * @descripe 从header中用户信息处理
     * @param {object} key 插入请求头的key
     * @param {object} val 插入请求头的value
     **/
    function getSetHeader$1(key,val){
      if(!checkValue(val)){return}
      let requestArr=getUserIdManageClass.requestArr;
      let configeManage=getUserIdManageClass.configeManage;
      if(requestArr.length>0){
        for(let i=0,j=requestArr.length-1;i<=j;i++){
          if(requestArr[i].rule==key){
            if(requestArr[i].index<=getUserIdManageClass.isStopGetValue){
              configeManage[requestArr[i].index]["value"]=""+val;
              getUserIdManageClass.checkValueRight();
              return
            }
          }
        }
      }
    }
    
    /**
     * @descripe setRequestHeader前的操作处理,1:请求头用户信息处理;2:请求头信息获取;3:reqht业务的处理;
     * @param {object} key 插入请求头的key
     * @param {object} val 插入请求头的value
    **/
    function beforeXHRHeader(key, val) {
      getSetHeader$1(key,val);
      if (!isDefined(this.$metric)) {
        return
      }
      getReqhead(key,val,this.$metric);
      var info = this.$metric.info;
        //增加取自定义请求头所有配置
      if (!isDefined(info[GC.REQUEST_HEADER])) {
        info[GC.REQUEST_HEADER] ='';
      } 
        info[GC.REQUEST_HEADER]=info[GC.REQUEST_HEADER]&&info[GC.REQUEST_HEADER]+"\r\n"+key+":"+val||key+":"+val;  
    }
      
    /**
     * @descripe 初始化xhr的hook
     **/
    function initXHR() {
        if (!window.XMLHttpRequest) {
          return log('C128')
        }
        if (XMLHttpRequest.prototype) { /* global XMLHttpRequest */
          XMLHttpRequest.prototype.open = hack(XMLHttpRequest.prototype.open, beforeXHROpen);
          XMLHttpRequest.prototype.send = hack(XMLHttpRequest.prototype.send, beforeXHRSend);
          XMLHttpRequest.prototype.setRequestHeader = hack(XMLHttpRequest.prototype.setRequestHeader, beforeXHRHeader);
        } else {
          log('C129');
          var XHR = window.XMLHttpRequest;
          window.XMLHttpRequest = function () {
            var ins = new XHR();
            ins.open = hack(ins.open, beforeXHROpen);
            ins.send = hack(ins.send, beforeXHRSend);
            ins.setRequestHeader = hack(ins.setRequestHeader, beforeXHRHeader);
      
            return ins
          };
        }
    }

  var callbackXhrIdentify={isPeriod:false,actionID:'',networkID:''};

  /**
   * @descripe 获取请求体
   * @return 根据不同请求体类型返回对应字符串
   **/
  function getBody (body) {
  return getRequestParam(body)
  }
  /**
   * @descripe 计算请求体大小
   **/
  function getBodySize (body) {
  return getContentSize(body)
  }
  /**
   * @descripe 获取请求头,序列化为字符串
   * @param {*} headers headers对象
   **/
  function getHeaders (headers) {
  if (!isDefined(headers)) {
      return ''
  }
  var allHeaders = '';
  try {
      if (window.Headers && headers instanceof Headers) { /* global Headers */
      allHeaders = map(iterate(headers.entries()), function (ent) {
          return ent.join(':')
      }).join("\r\n");
      } else {
      var headersCache = [];
      forEachOwn(headers, function (val, key) {
          headersCache.push(key + ':' + val);
      });
      allHeaders = headersCache.join("\r\n");
      }
  } catch (e) {
      allHeaders = '';
      log('C150');
  }
  return allHeaders
  }
  /**
   * @descripe 判断是否是request对象,fetch首个参数可以是字符串或者request对象
   * @param {object} request 参数
   **/
  function isRquest (request) {
  return isDefined(request) && typeof request !== 'string'
  }
  /**
   * @descripe 从resource或者init中获取child属性值
   **/
  function getChild (resource, init, child) {
  if(child==='headers' && init ){
      if(isRquest(resource)&&resource[child]){
      var result=extend(init[child],resource[child]);
      return result
      }else {
      return init[child]
      }
  }
  return isRquest(resource) ? resource[child] : init ? init[child] : null
  }
  /**
   * @descripe 从resource和init中获取请求体和请求头
   **/  
  function parseRequestAndHeaders(resource, init) {
      return {
        requestBody: getBody(getChild(resource, init, 'body')),
        requestHeader: getHeaders(getChild(resource, init, 'headers'))
      }
  }
  /**
   * @descripe 解析请求url与method等基础信息
   * @param {*} resource fetch的参数一
   * @param {*} init fetch的参数二
   **/
  function parsePathAndMethod(resource, init) {
    let url = isRquest(resource) ? resource.url : resource;
    url = getUrl$1(url);
    let method = toUpper(getChild(resource, init, 'method')) || 'GET';
    let ipPort = getIP(url);
      return {
        id:uuid(),
        url: url.slice(0,4096),
        method: method,
        ip:ipPort[0]||'',
        port: ipPort[1]||'',
        protocalType: url.indexOf('https')>-1 ? 2 : 1,
        reqUrlDta:isDefined(GS.sett.reqURLKey || GS.secondSett.reqURLKey) &&getParams(url)||'',
        requestType:4
      }
  }
    


  function requestEnd ($metric, response) {
      if (!$metric) {
          return
      }
      extendMetrics($metric);
      polyfillMetric($metric);

  var requestMetric = $metric.metric;
  if (!isDefined(requestMetric[GC.DECODED_BODY_SIZE]) || requestMetric[GC.DECODED_BODY_SIZE] <= 0) {
      var requestExt = $metric.ext || {} ;
      requestMetric[GC.DECODED_BODY_SIZE] = requestExt.originalResponseSize || 0 ;
  }
  notifierEmit({ t: GC.REQUEST_DATA, p: $metric ,isRelatedH5:isDefined($metric.info.isRelatedH5)?true:false});
  setTimeout(function(){getCookieUserID();},50);
  }

  function hackFetch () {
      var $fetch = window.fetch;
      window.fetch = function (resource, init) {
        let _resource=typeof resource ==="object" ?JSON.parse(JSON.stringify(resource)):resource;
        // resource可传入url字符串，location对象，也传request对象  https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch#%E8%87%AA%E5%AE%9A%E4%B9%89%E8%AF%B7%E6%B1%82%E5%AF%B9%E8%B1%A1
        if(typeof resource !=="string"&&resource&&(resource.href||resource.url)){
          _resource=resource.href||resource.url||'';
        }
        var replayUrl=isDefined(window.$bonreeReplayUrl)?window.$bonreeReplayUrl:null;
        var requestInfo = parsePathAndMethod(_resource, init);
        if(!isRquest(_resource)&&_resource.indexOf(replayUrl)===-1 || isRquest(_resource)){
          notifierEmit({t:GC.LIFESTYLE_FETCH_START,info:requestInfo});
        }
        /*检测是否在关联action的xhr回调中调用*/
        if(callbackXhrIdentify.isPeriod){
          requestInfo.ai=callbackXhrIdentify.actionID;
          requestInfo.parentNetworkID=callbackXhrIdentify.networkID;
          notifierEmit({t:GC.LIFESTYLE_CALLBACK_REQUEST_START+requestInfo.ai});
        }
        requestInfo=extend(requestInfo,{"reqhtData":{},"reshtData":{}});
        /*精确ent*/
        requestInfo['timestamp']=now();
        if(isDefined(GS.sett)&&isDefined(GS.sett.pageViewId)){
          requestInfo['pageViewId']=GS.sett.pageViewId;
        }
        /*检测是否开启brss*/
        BWexample.checkIsOpen();
        if(BWexample.isOpen){
          extend(requestInfo,{"reqhtData":{},"reshtData":{}});
          let obj=checkBlackAndWhite(requestInfo,"_fetch");
          if(isDefined(obj)&&isObj(obj)){
            forEachOwn(obj,function(val,key){
              let data=val;
              if(isObj(val)){
                if(val.sky){
                  data=val.fun(val.url,val.pathname);
                }else {
                  data=val.fun(val.len);
                }
              }
              if(startWith(val,"bnro=")){
                data+="_fetch_fetch";
              }
              /*需要将请求头信息转化为{}*/
              if(isDefined(init)){
                if(isDefined(init.headers)){
                  /*headers可能是Headers实例,getSetHeader用到的是字典*/
                  if(init.headers instanceof Headers){
                      let headersDict = {};  
                      for(let pair of init.headers.entries()) {  
                          headersDict[pair[0]] = pair[1];  
                      }
                      init.headers=headersDict;  
                  }
                  /*加上插入的请求头*/
                  extend(init.headers,{
                      [key]:data
                      });
                }else {
                  let head={
                    [key]:data
                  };
                  extend(init,{headers:head});
                }
              }else {
                /*没有直接赋予请求头值*/
                init={headers:{
                  [key]:data
                }};
              }
            });
          }
        }

        if(init&&init.headers){
          /*有可能没有插入转换*/
          if(init.headers instanceof Headers){
            let headersDict = {};  
            for(let pair of init.headers.entries()) {  
                headersDict[pair[0]] = pair[1];  
            } 
            init.headers=headersDict;
            getSetHeader(init.headers,requestInfo);
          }else {
            getSetHeader(init.headers,requestInfo);
          } 
        }
        requestInfo.type = 1;
        extend(requestInfo, getTime());
        var $fetchPromise = $fetch(resource, init);
        extend(requestInfo, parseRequestAndHeaders(_resource, init));
        var $metric = { info: requestInfo };
        var requestMetric = $metric.metric = {};
        requestMetric[GC.UPLOAD_BODY_SIZE] = getBodySize(getChild(_resource, init, 'body'));
        return $fetchPromise.then(function (e) {
          requestInfo.status = e.status;
          requestInfo.statusText = e.statusText;
          var endTime = requestMetric[GC.RESPONSE_END] = tillNow();
          requestMetric[GC.RESPONSE_START] = requestMetric[GC.CALLBACK_START] = endTime;
          queueRequest($metric); // 添加请求记录
          var oriArr = getHeaders(e.headers);
          var allHeaders=oriArr;
          var allHeadersStr=toLower(allHeaders);
          var arr = allHeaders.trim().split(/[\r\n]+/);
          var headerMap = {};
          arr.forEach(function (line) {
            var parts = line.split(':');
            var header = parts.shift();
            var value = parts.join(": ");
            headerMap[header] = value;
          });
          // requestInfo.guid = allHeadersStr.indexOf(GC.GUID_KEY) > -1 ? headerMap[GC.GUID_KEY].split(',')[0] : '';
          // requestInfo.xBrResponse=allHeadersStr.indexOf(GC.X_BR_RESPONSE)>-1 ? headerMap[GC.X_BR_RESPONSE].split(',')[0]:'';
          // requestInfo.traceResponse=allHeadersStr.indexOf(GC.TRACE_RESPONSE)>-1 ? headerMap[GC.TRACE_RESPONSE].split(',')[0]:''; 
          requestInfo.guid = isDefined(headerMap[GC.GUID_KEY]) && headerMap[GC.GUID_KEY].split(',')[0] || '';
          requestInfo.xBrResponse=isDefined(headerMap[GC.X_BR_RESPONSE]) && headerMap[GC.X_BR_RESPONSE].split(',')[0]||'';
          requestInfo.traceResponse=isDefined(headerMap[GC.TRACE_RESPONSE]) && headerMap[GC.TRACE_RESPONSE].split(',')[0]||''; 
          requestInfo[GC.RESPONSE_HEADER] = withLength(allHeaders, 2000);
          try {
            var respHeaderTraceKeys=[];
            if(isDefined(GS.sett.respHeaderTraceKey)&&GS.sett.respHeaderTraceKey.length>0 || isDefined(GS.secondSett.respHeaderTraceKey)&&GS.secondSett.respHeaderTraceKey.length>0){
              /*合并配置,先将匹配的匹配上*/
              if(isDefined(GS.secondSett.respHeaderTraceKey)&&GS.secondSett.respHeaderTraceKey.length>0){
                if(isDefined(GS.sett.respHeaderTraceKey)){
                  respHeaderTraceKeys=GS.sett.respHeaderTraceKey.concat(GS.secondSett.respHeaderTraceKey);
                }else {
                  respHeaderTraceKeys=GS.secondSett.respHeaderTraceKey;
                }
              }else {
                if(isDefined(GS.sett.respHeaderTraceKey)){
                  respHeaderTraceKeys=GS.sett.respHeaderTraceKey;
                } 
              }
              for(let i=0,j=respHeaderTraceKeys.length-1;i<=j;i++){
                 if(allHeadersStr.indexOf(toLower(respHeaderTraceKeys[i])) > -1){
                  requestInfo['reshtData'][respHeaderTraceKeys[i]]=e.headers.get(respHeaderTraceKeys[i]);
                 }
              }
            }
          } catch (error) {
            log("C148");
          }

          getResponseHead(oriArr);
          e.$metric = $metric;
          requestMetric[GC.CALLBACK_END] = tillNow();
          const cloneData=tryToClone(e);
          if(cloneData){
            try {
              const options={
                bytesLimit: Number.POSITIVE_INFINITY,
                collectStreamBody: true,
              };
              readBytesFromStream(cloneData.body,options,function(res){
                $metric.ext = { originalResponseSize: res };
                requestEnd($metric,e);
              });
            } catch (error) {
              log("C149");
            }
          }else {
            requestEnd($metric);
          }
          return e
        }, function (e) {
          var endTime = requestMetric[GC.RESPONSE_END] = tillNow();
          requestMetric[GC.RESPONSE_START] = requestMetric[GC.CALLBACK_START] = requestMetric[GC.CALLBACK_END] = endTime;
          requestInfo.status = window.TypeError && e instanceof TypeError ? 602 : 600;
          requestInfo.eType="FETCH";
          requestInfo[GC.STATUS_TEXT]=requestInfo.status==602?'FETCH request exception':'User terminates FETCH request';
          requestEnd($metric);
          throw e
        }).catch(err => {
          err.type=2;
          throw err
        }
        )
      };
  }
  /**
   * @descripe 1:对请求头进行用户ID匹配处理;2:reqht业务处理;
   **/
  function getSetHeader(head,requestInfo){
    if(!isDefined(head)){
      return 
    }
    let requestArr=getUserIdManageClass.requestArr;
    let configeManage=getUserIdManageClass.configeManage;
    if(requestArr.length>0){
      for(let i=0,j=requestArr.length-1;i<=j;i++){
        if(head.hasOwnProperty(requestArr[i].rule)){
          if(requestArr[i].index<=getUserIdManageClass.isStopGetValue){
            if(checkValue(head[requestArr[i].rule])){
              configeManage[requestArr[i].index]["value"]=""+head[requestArr[i].rule];
              getUserIdManageClass.checkValueRight();
              return
            }
          }
        }
      }
    }
    if(isDefined(GS.sett.reqHeaderTraceKey)&&GS.sett.reqHeaderTraceKey.length>0 || isDefined(GS.secondSett.reqHeaderTraceKey)&&GS.secondSett.reqHeaderTraceKey.length>0){
      /*合并配置*/
      var reqHeaderTraceKeys=[];
      if(isDefined(GS.secondSett.reqHeaderTraceKey)&&GS.secondSett.reqHeaderTraceKey.length>0){
         if(isDefined(GS.sett.reqHeaderTraceKey)){
            reqHeaderTraceKeys=GS.sett.reqHeaderTraceKey.concat(GS.secondSett.reqHeaderTraceKey);
         }else {
            reqHeaderTraceKeys=GS.secondSett.reqHeaderTraceKey;
         }
      }else {
        if(isDefined(GS.sett.reqHeaderTraceKey)){
          reqHeaderTraceKeys=GS.sett.reqHeaderTraceKey;
        }
      }
      Object.keys(head).map(function(item){
        if(includes(reqHeaderTraceKeys.map(function(value){return value.toLowerCase()}),item.toLowerCase())){
          requestInfo["reqhtData"][item]=head[item];
        }
      });
    }
  }

    function initFetch () {
      if (!isFunction(window.fetch)) {
        return log('C147')
      }
      notifierOn(GC.XHR_CALLBACK_IDENTIFY,function(ext){
          callbackXhrIdentify=ext.info;
      });
      hackFetch();
    }

  function initRequestCollector() {
      initXHR();
      initFetch();
      if (window.performance && window.performance.now) {
          initDeamon();
        }
  }

  function umustFiledHandle(builddata){
      let eventStruct=builddata.data;
      if(isDefined(eventStruct.al)&&eventStruct.al===""){
        delete eventStruct.al;
      }
      return builddata
    }
  /*
  获取客户端类型1:pc 2:移动
  */
  function getClientType() {
      try {
          let phone = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
          if (phone) {
              return 2
          }
          return 1
      } catch (error) {
        log('C119');
      }
  }
  /*
  @param data:对采集的原始路由数据处理组包
  */
  function routeService(data) {
      const baseData = new Metric(data.p, GC.ROUTE);
      let ctp=getClientType();
      baseData.info(GC.URL, '', 'tu')
          .info(GC.REFERRER, '', 'fu')
          .info(GC.DURATION, 0, 'd')
          .info(GC.STATUS, 0, 'sta')
          .info(GC.ALIAS, '', 'al')
          .info(GC.PATH, '', 'pt')
          .info(GC.ROOT, '', 'rt')
          .info(GC.FULL_URL, '', 'pu')
          .info(GC.FRAME_WORK, '', 'fw')
          .info(GC.CUSTOM_IC, false, 'ic')
          .info(GC.CLIENT_TYPE,ctp,'ctp')
          .info('pvid','','pvid')
          .info('ns',0,'ns');
          if(isDefined(data.p.info['wri'])){
            baseData.info('wri',[],'wri');
          }
          var buildData=baseData.build();
          if(isDefined(data.revts)&&data.revts.length>0){
            buildData.revts=data.revts;
          }
      return umustFiledHandle(buildData);
  }

  var currentLocation=isDefined(window.location)?window.location:'';
  /*
  粗略判断框架类型
  */
  function getFramework(){
      if(!window){
          return "Other"
      }
      if(typeof window.Vue !== 'undefined'||window.__VUE__){
          return "Vue"
      }
      if(window.$nuxt&&window.$nuxt._isVue){
          return "Vue"
      }
      if(window.React){
          return "React"
      }
      if(typeof window.ng !== 'undefined' || isDefined(window.Zone)|| isDefined(window.angular)){
          return "Angular"
      }
      return 'Other'
  }
  /*hasHandleRecord:因为存在切换后立即切换,此时需要闭包*/
  var storageResource=[];
  var hasHandleRecord={};

  /*路由切换时的回调*/
  function onLocationChange() {
      if (currentLocation.href.split('?')[0] === (isDefined(location)?location.href:'').split('?')[0]){
        return
      }
      let actionInfo={id:""};
      notifierEmit({t:GC.ROUTE_CHANGE_START,info:actionInfo});
      /*此处是切换后回调没有调用就切换了其它地址路由,此时强制闭包数据*/
      if(isDefined(hasHandleRecord)&&Object.getOwnPropertyNames(hasHandleRecord).length>0){
          var uuidKeys=Object.keys(hasHandleRecord);
          uuidKeys.map((key) => {
            if(typeof hasHandleRecord[key]==='function'){
              hasHandleRecord[key]();
              delete hasHandleRecord[key];
            } 
          });
        }
      GS.sett.isSinglePage=true;
      GS.sett.pageViewId=uuid();
      const newLocation = extend({},location);
      /*
      {url:tu,referrer:fu,duration:d,status:sta,alias:al,path:pt,root:rt,fullUrl:pu}
      */
      var info={
          info:{
          uuid:uuid(),
          timestamp:now(),
          url:newLocation.href,
          referrer: extend({},currentLocation).href,
          duration:1000,
          status:0,
          path:newLocation.hash===""?newLocation.pathname:newLocation.hash,
          root:newLocation.hash===""?newLocation.origin+newLocation.pathname:newLocation.origin+newLocation.pathname+newLocation.hash.replace("#/",''),
          fullUrl:newLocation.hash!==""?newLocation.origin+newLocation.pathname:newLocation.origin+"/",
          framework:getFramework(),
          pvid:GS.sett.pageViewId,
          ns:isDefined(performance)&&isDefined(performance.timing)?performance.timing.navigationStart:0
        }};
      if(info.info.url.indexOf('?')>-1){
          info.info.url=info.info.url.split('?')[0];
      }
      if(info.info.referrer.indexOf('?')>-1){
          info.info.referrer=info.info.referrer.split('?')[0];
      }
      if(info.info.path.indexOf('?')>-1){
          info.info.path=info.info.path.split('?')[0];
      }
      if(info.info.root.indexOf('?')>-1){
          info.info.root=info.info.root.split('?')[0];
      }
      if(info.info.fullUrl.indexOf('?')>-1){
          info.info.fullUrl=info.info.fullUrl.split('?')[0];
      }
      var callBack=function(){
          if(!(isDefined(hasHandleRecord)&&isDefined(hasHandleRecord[info.info.uuid]))){
              return
            }
          if(isDefined(hasHandleRecord)&&isDefined(hasHandleRecord[info.info.uuid])){
              delete hasHandleRecord[info.info.uuid];
             }
          let routeEvent=routeService({
              p:info
          });
          /*发布给订阅者*/
          const {type:k,ent:ent,sin:sin,data:v}=routeEvent;
          notifierEmit({t:GC.ROUTE_CHANGE_END+actionInfo.id,routeData:{k,ent,sin,v}});
      };
      if(isDefined(hasHandleRecord)){
          hasHandleRecord[info.info.uuid]=callBack;
      }
      var handleTimer=setTimeout(callBack,1000);
      var pageActivityManage=new PageActivityManager(
          function(entriesArr){
                  entriesArr.forEach(entrie => {
                      //wri转化
                      var entries={
                          st:getFixedMetric(entrie,GC.START_TIME),
                          name:sensitiveRuleHandle({p:{info:{url:entrie[GC.NAME]}}},GS.sett).p.info.url,
                          dura:isDefined(entrie[GC.DURATION])?getFixedMetric(entrie,GC.DURATION):(entrie[GC.RESPONSE_END] - entrie[GC.START_TIME]),
                          rt:getMineTypeByUrl(entrie[GC.NAME]),
                          fs:getFixedMetric(entrie,GC.FETCH_START),
                          dls:getFixedMetric(entrie,GC.DOMAIN_LOOKUP_START),
                          dle:getFixedMetric(entrie,GC.DOMAIN_LOOKUP_END),
                          cs:getFixedMetric(entrie,GC.CONNECT_START),
                          ce:getFixedMetric(entrie,GC.CONNECT_END),
                          scs:getFixedMetric(entrie,GC.SECURE_CONNECTION_START),
                          reqs:getFixedMetric(entrie,GC.REQUEST_START),
                          rsps:getFixedMetric(entrie,GC.RESPONSE_START),
                          rspe:getFixedMetric(entrie,GC.RESPONSE_END),
                          rs:isDefined(entrie[GC.RESPONSE_STATUS])?entrie[GC.RESPONSE_STATUS]:-1
                      };
                      if(isDefined(entrie[GC.INITIATOR_TYPE])){
                          entries.it=entrie[GC.INITIATOR_TYPE];
                      }
                      if(isDefined(entrie[GC.DECODED_BODY_SIZE])){
                          entries.ts=entrie[GC.TRANSFER_SIZE];
                          entries.ebs=entrie[GC.ENCODED_BODY_SIZE]>=Math.pow(2,64)?Math.pow(2,60):entrie[GC.ENCODED_BODY_SIZE];
                          entries.dbs=entrie[GC.DECODED_BODY_SIZE];
                      }else {
                          entries.ts=0;
                          entries.ebs=0;
                          entries.dbs=0;
                      }
                      /*resource*/
                      if (isDefined(entries.it)) {
                          if((entries.it!=='xmlhttprequest'&&entries.it!=='fetch')){
                              storageResource.push(entries);
                          }
                       }else {
                          storageResource.push(entries);
                       }  
                   });
              if(isDefined(handleTimer)){
                  clearTimeout(handleTimer);
                  handleTimer=setTimeout(callBack,1000);
              }
          }
      );
      pageActivityManage.turnOnRecord();
      pageActivityManage.startPageActivityObserver();
      //处理数据
      callBack=function(){
          if(!(isDefined(hasHandleRecord)&&isDefined(hasHandleRecord[info.info.uuid]))){
              pageActivityManage.turnOffRecord();
              pageActivityManage.stopPageActivityObserver();
              return
            }
          if(isDefined(hasHandleRecord)&&isDefined(hasHandleRecord[info.info.uuid])){
              delete hasHandleRecord[info.info.uuid];
             }
          if(pageActivityManage.mutationRecord.length>0){
              if(pageActivityManage.performanceRecord.length>0){
                  var performanceRecordMax=pageActivityManage.performanceRecord.pop();
                  var mutationRecordMax=pageActivityManage.mutationRecord.pop();
                  info.info.duration=performanceRecordMax-mutationRecordMax>0?performanceRecordMax-info.info.timestamp:mutationRecordMax-info.info.timestamp;
              }else {
                  info.info.duration=pageActivityManage.mutationRecord.pop()-info.info.timestamp;
              }
          }else {
              if(pageActivityManage.performanceRecord.length>0){
                  info.info.duration=pageActivityManage.performanceRecord.pop()-info.info.timestamp;
              } 
          }
          pageActivityManage.turnOffRecord();
          pageActivityManage.stopPageActivityObserver();
          if(isDefined(info)){
              if(isDefined(storageResource)&&storageResource.length>0){
                  info.info.wri=storageResource;
              }
          }
          let routeSettEvent=routeService({
              p:info
          });
          /*发布给订阅者*/
          const {type:k,ent:ent,sin:sin,data:v}=routeSettEvent;
          notifierEmit({t:GC.ROUTE_CHANGE_END+actionInfo.id,routeData:{k,ent,sin,v}});
          if(isDefined(storageResource)){
              storageResource=[];
          }
      };
      if(isDefined(hasHandleRecord)){
          hasHandleRecord[info.info.uuid]=callBack;
        }
      currentLocation = newLocation;
    }
  class LocationChangeObserver{
      constructor(Location){
          this.currentLocation = extend({},Location);
          currentLocation=this.currentLocation;
      }
      trackHistory(){
          const orginPushState=history.pushState;
          const orginReplaceState=history.replaceState;
          if(isDefined(orginPushState)&&!isDefined(orginPushState.$hasHooked)){
              history.pushState=function(state, title, url){
                  orginPushState.apply(this,[state, title, url]);
                  onLocationChange();
              };
              history.pushState.$hasHooked=true;
          }
          if(isDefined(orginReplaceState)&&!isDefined(history.replaceState.$hasHooked)){
              history.replaceState=function(state, title, url){
                  orginReplaceState.apply(this,[state, title, url]);
                  onLocationChange();
              };
              history.replaceState.$hasHooked=true;
          }
          window.addEventListener("popstate",onLocationChange);
      }
      trackHashchage(){
          window.addEventListener('hashchange',onLocationChange);
      }
      init(){
          this.trackHistory();
          this.trackHashchage();
      }
  }

  /*路由切换数据采集*/
  function listenRouter() {
      var locationChangeObserver=new LocationChangeObserver(isDefined(window.location)?window.location:'');
      locationChangeObserver.init();
      return locationChangeObserver
  }

  var websocketSendStart=0;
  function beforeWebsocketSend(content){
      websocketSendStart=new Date().getTime()*1000;
  }
  /*send结束后调用,获取发送大小*/
  function afterWebsocketSend(content){
      if(isDefined(content)){
          if(content.constructor.toString().indexOf("String")>-1){
              if(isDefined(window.TextEncoder)){
                  var encoder = new TextEncoder();
                  var size=encoder.encode(content).length;
              }else {
                  var size=content.length;
              }  
          }
          if(content.constructor.toString().indexOf("ArrayBuffer")>-1){
              var size=content.byteLength;
          }
          if(content.constructor.toString().indexOf("Blob")>-1){
              var size=content.size;
          }
          if(content.constructor.toString().indexOf("Array")>-1){
              var size=content.byteLength;
          }
          var domain=isDefined(this.name)?this.name:this.url.split('?')[0];
          try{
              if(/^[a-zA-Z0-9:_-\s@./]+$/.test(domain)===false){
                  return
              }
              var spanWebsocket=new SpanStruct(domain,'websocket');
              spanWebsocket.setStatus(1);
              if(isDefined(spanWebsocket.spanEvent)&&isDefined(spanWebsocket.spanEvent.ic)){
                  spanWebsocket.spanEvent.ic=false;
              }
              spanWebsocket.setTag('process','send');
              spanWebsocket.setTag('connectID',isDefined(this.identify)?this.identify:uuid());
              spanWebsocket.setData("url",isDefined(this.handledUrl)?this.handledUrl:this.url);
              var duration=new Date().getTime()*1000-websocketSendStart;
              if(duration===0){
                  duration=999;
              }
              if(isDefined(this.readyState)&&(this.readyState===2||this.readyState===3)){
                  spanWebsocket.setStatus(2);
                  spanWebsocket.setStatusCode('WebSocket is already in CLOSING or CLOSED state.');
              }
              spanWebsocket.setMetric('send',duration,'us');
              spanWebsocket.setDuration(duration);
              spanWebsocket.setMetric('size',size,'byte');
              spanWebsocket.finish();
          }catch(e){
              
          }
          
      }

  }
  function hackWebsocket(){
      var $originWebsocket=window.WebSocket;
      window.WebSocket.prototype.send=hack(window.WebSocket.prototype.send,beforeWebsocketSend,afterWebsocketSend);
      window.WebSocket=function(){
          notifierEmit({t:GC.WEBSOCKET_CONNECTION_START});
          let callTime=new Date().getTime()*1000;
          var $WebSocketObj= arguments[1]===undefined?new $originWebsocket(arguments[0]):new $originWebsocket(arguments[0],arguments[1]);
          var name=$WebSocketObj&&$WebSocketObj.url&&$WebSocketObj.url.indexOf('?')>-1?$WebSocketObj.url.split("?")[0]:$WebSocketObj.url;
          var handledUrl=sensitiveRuleHandle({p:{info:{url:$WebSocketObj.url}}},GS.sett).p.info.url;
          $WebSocketObj.handledUrl=isDefined(handledUrl)?handledUrl:"";
          $WebSocketObj.identify=uuid();
          $WebSocketObj.name=isDefined(name)?name:"";
          $WebSocketObj.hasHandleConnect=false;
          $WebSocketObj.addEventListener("open",function(){
              //链接完成时机
              if(/^[a-zA-Z0-9:_-\s@./]+$/.test(name)===false){
                  return
              }
              var spanWebsocket=new SpanStruct(name,'websocket');
              spanWebsocket.spanEvent.st=0;
              spanWebsocket.spanEvent.timestamp=callTime;
              spanWebsocket.setStatus(1);
              if(isDefined(spanWebsocket.spanEvent)&&isDefined(spanWebsocket.spanEvent.ic)){
                  spanWebsocket.spanEvent.ic=false;
              }
              spanWebsocket.setTag('process','connect');
              spanWebsocket.setTag('connectID',isDefined($WebSocketObj.identify)?$WebSocketObj.identify:uuid());
              spanWebsocket.setData("url",$WebSocketObj.handledUrl);
              spanWebsocket.setDuration(new Date().getTime()*1000-callTime);
              spanWebsocket.finish();
              $WebSocketObj.hasHandleConnect=true;
              notifierEmit({t:GC.WEBSOCKET_CONNECTION_END});
          }
          
          );
          $WebSocketObj.addEventListener("error", function (event) {
              if(!$WebSocketObj.hasHandleConnect){
                  if(/^[a-zA-Z0-9:_-\s@./]+$/.test(name)===false){
                      return
                  }
                  //链接过程中发生错误
              var spanWebsocket=new SpanStruct(name,'websocket');
              spanWebsocket.spanEvent.st=0;
              spanWebsocket.spanEvent.timestamp=callTime;
              spanWebsocket.setStatus(2);
              if(isDefined(spanWebsocket.spanEvent)&&isDefined(spanWebsocket.spanEvent.ic)){
                  spanWebsocket.spanEvent.ic=false;
              }
              spanWebsocket.setTag('process','connect');
              spanWebsocket.setTag('connectID',isDefined($WebSocketObj.identify)?$WebSocketObj.identify:uuid());
              spanWebsocket.setData("url",$WebSocketObj.handledUrl);
              spanWebsocket.setDuration(new Date().getTime()*1000-callTime);
              spanWebsocket.setStatusCode("Websocket connection failed");
              spanWebsocket.finish();
              $WebSocketObj.hasHandleConnect=true;
              notifierEmit({t:GC.WEBSOCKET_CONNECTION_END});
              }
            });
          return $WebSocketObj
  };   
      /*某些第三方封装库会对实例简单校验*/
      window.WebSocket=extend(window.WebSocket,$originWebsocket); 
      window.WebSocket.prototype=$originWebsocket.prototype;   
  }
  function initWebsocket(){
      if(GS.sett.enableWebsocket===false) return
      if(window.WebSocket===undefined){
          log("C157");
          return
      }
      if(window.WebSocket.prototype===undefined){
          log("C158");
          return
      }
      hackWebsocket();
  }

  var defaultAPI = {
      config: NIL_FN,
      error: NIL_FN,
      recordCustomActionEnd: NIL_FN
  };

  function dataEngine() {
      if (typeof document === "undefined" || !GS.sett.probability || window.bonreeRUM) {
          log("C105");
          return window.bonreeRUM || defaultAPI
      }
      // 启动探针
      // 路由监控
      listenRouter();
      initError();
      initDocumentCollector();
      initRequestCollector();
      initConsole();
      initActionCollector();
      initWebsocket();
      if(isDefined(GS.sett.RecordConfiguration || GS.sett.mc)){
          if(isDefined(window.BonreeRecord)&&isDefined(window.BonreeRecord.BonreeRecord)){
              window.stopBonreeRecord=window.BonreeRecord.BonreeRecord(GS.sett);
          }else if(isDefined(window.BonreeAgent)&&window.BonreeAgent.BonreeRecord){
              window.stopBonreeRecord=window.BonreeAgent.BonreeRecord(GS.sett);
          }
          else {
              log("C155");
          }
       }
      var bonreeRUM = overwrite(defaultAPI, {
          config: function(data,isFirstSet=true,from=0){
              /*android在回调中注入多次,若前置配置是安卓说明安卓已经实例化了,安卓再次注入忽略*/
              if(isDefined(data.osType)&&data.osType===GC.ANDROID&&GS.sett.osType===GC.ANDROID){
                  return
              }
              GS.setConfig.call(GS,data,isFirstSet,from);
              /*若包含appId字段说明后置配置是brsower配置,需要更新appid*/
              if(isDefined(data.appId)){
                  sessionM.setAppid(data);
              }
          },
          error: error,
          recordCustomActionEnd: recordCustomActionEnd
      });
      if(isDefined(window)){
          window.bonreeRUM = bonreeRUM;
      }
      window.bonreeRUM.version=version;
      /*挂载startSpan*/
      window.bonreeRUM.startSpan=function(name,type){
          return new SpanStruct(name,type)
      };
      /*回放模块需要sessionID*/
      window.bonreeRUM.getSession=function(){
          return sessionM.getSession().sessionID
      };
      /*回放模块需要用户信息*/
      window.bonreeRUM.getUserInfo=function(){
          return globalData.getUserInfo()
      };
      /*更新配置appid信息接口*/
      window.bonreeRUM.updateConfig=function(config){
          if(isDefined(window.stopBonreeRecord)){
              window.stopBonreeRecord();
              window.stopBonreeRecordUpload=true;
          }
          flushData();
          sessionM.setAppid(config);
      };
      /*window挂载bonreeJsBridge,兼容历史*/
      window.bonreeJsBridge=jsBridge;
      /*将bonreeJsBridge接口同步bonreeRUM*/
      window.bonreeRUM=extend(window.bonreeRUM,jsBridge);
  }

  function actionService(data){
      let baseData=new Metric(data.p,GC.ACTION);
      baseData.info("t")
      .info("n")
      .info("sa")
      .info("i")
      .info("vn")
      .info("ic")
      .info("p","","p",true)
      .info("lt")
      .info("is")
      .info("id")
      .info("m")
      .info("ice")
      .info("ci")
      .info("vt",1,"vt")
      .info("vci","","vci");
      if(isDefined(data.p.info.me)){
          baseData.info('me');
      }
      let buildData=baseData.build();
      if(isDefined(data.revts)&&data.revts.length>0){
          buildData.revts=data.revts;
      }
      return buildData;
  }

  /*console事件的数据服务*/
  function consoleService(data){
      const baseData = new Metric(data.p, GC.CONSOLE);
      baseData.info('lv')
      .info('msg', '', 'msg',true);
      return baseData.build();
  }

  /*jserror的数据服务*/
  function errorService(data) {
      let ua = ((typeof window !== 'undefined' && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : "");
      const baseData = new Metric(data.p, GC.ERROR);
      const pct=isDefined(window.performance)&&isDefined(window.performance.timing)&&performance.timing.navigationStart||1;
      //provide to BrLog
      isDefined(window.BRLog)&&window.BRLog.__sendErrorInfo(baseData.data.info);
      baseData.info(GC.PAGE_ID, '', 'pvid')
          .info(GC.PAGE_URL, '', 'url')
          .info(GC.ERROR_FILE, '', 'n')
          .info(GC.MESSAGE, '', 'm')
          .info(GC.ERROR_LINE, 0, 'l')
          .info(GC.ERROR_COLUMN, 0, 'col')
          .info(GC.PAGE_CREATE_TIME, pct*1000, 'pct')
          .info(GC.PAGE_TITLE, document.title||"noTitle", 't')
          .info('type',3,'ect')
          .info('ua',ua,'ua');
          if(isDefined(data.p.info[GC.NAME]&&data.p.info[GC.NAME]!=='')){
              baseData.info(GC.NAME,'','et');
          }
          if(isDefined(data.p.info[GC.ERROR_STACK])&&data.p.info[GC.ERROR_STACK]!==''){
              baseData.info(GC.ERROR_STACK,'','sta');
          }else {
              /*一种匿名错误的处理*/
              if(isDefined(baseData.data.info['file'])){
                  baseData.data.info[GC.ERROR_STACK]="undefined at @"+baseData.data.info['file'];
                  baseData.info(GC.ERROR_STACK,'at undefined @ '+baseData.data.info['file'],'sta');
              }   
          }
          if(isDefined(GS.sett.isSinglePage)){
              baseData.info('pt',2,'pt');
          }else {
              baseData.info('pt',1,'pt');
          }
      return baseData.build();
  }

  let h5Event={
      "pvid":"",  //page id 页面id [非空字段]
      "url":"",   //requesturl 请求地址 [非空字段]
      "wpi":{},   //WebviewPerformanceInfo 页面性能数据 [非空字段]
      "wri":[], //WebviewResourceInfo 页面资源数据 [非必要字段]
      "ic":false, //is custom 是否是自定义 [默认值false,非空字段]
      "timestamp":isDefined(performance.timing)&&performance.timing.navigationStart?performance.timing.navigationStart*1000:now()
  };
  /**
   * @description 主文档性能数据处理
   * @param {*} data 回调主文档数据
   **/
  function WebviewPerformanceInfoHandle(data){
      if(isDefined(data.p.info[GC.PAGE_ID])){
          h5Event.pvid=data.p.info[GC.PAGE_ID];
      }
      if(isDefined(data.p.info[GC.PAGE_URL])){
          h5Event.url=data.p.info[GC.PAGE_URL];
      }
      const baseData = new Metric(data.p, GC.WEBVIEWDATA);
      baseData.metric(GC.NAVIGATION_START, '', 'ns')
          .metric(GC.UNLOAD_EVENT_START, 0, 'ues')
          .metric(GC.FULL_RESOURCE_LOAD_TIME, 0, 'frlt')
          .metric(GC.UNLOAD_EVENT_END, 0, 'uee')
          .metric(GC.REDIRECT_START, 0, 'rds')
          .metric(GC.REDIRECT_END, 0, 'rde')
          .metric(GC.FETCH_START, 0, 'fs')
          .metric(GC.DOMAIN_LOOKUP_START, 0, 'dls')
          .metric(GC.DOMAIN_LOOKUP_END, 0, 'dle')
          .metric(GC.CONNECT_START, 0, 'cs')
          .metric(GC.SECURE_CONNECTION_START, 0, 'scs')
          .metric(GC.CONNECT_END, 0, 'ce')
          .metric(GC.REQUEST_START, 0, 'reqs')
          .metric(GC.RESPONSE_START, 0, 'rsps')
          .metric(GC.RESPONSE_END, 0, 'rspe')
          .metric(GC.DOM_LOADING, 0, 'dl')
          .metric(GC.DOM_INTERACTIVE, 0, 'di')
          .metric(GC.DOM_CONTENT_LOADED_EVENT_START, 0, 'dcles')
          .metric(GC.DOM_CONTENT_LOADED_EVENT_END, 0, 'dclee')
          .metric(GC.DOM_COMPLETE, 0, 'dc')
          .metric(GC.LOAD_EVENT_START, 0, 'les')
          .metric(GC.LOAD_EVENT_END, 0, 'lee')
          .metric(GC.FIRST_PAINT, 0, 'fp')
          .metric(GC.FIRST_CONTENTFUL_PAINT, 0, 'fcp')
          .metric(GC.LARGEST_CONTENTFUL_PAINT, 0, 'lcp')
          .metric(GC.TRANSFER_SIZE, 0, 'ts')
          .metric(GC.ENCODED_BODY_SIZE, 0, 'ebs')
          .metric(GC.DECODED_BODY_SIZE, 0, 'dbs')
          .metric('tti', 0, 'tti')
          .metric(GC.RESPONSE_STATUS, -1, 'rs');
          h5Event.wpi=baseData.build().data;
          const {type:k,ent:ent,sin:sin,data:v}=WebviewPerformanceToNet(WebviewPerformanceTimingTransformNet(h5Event.wpi,h5Event.url,h5Event.pvid));
          h5RelatedEvents.push(JSON.parse(JSON.stringify({k,ent,sin,v})));
          v.ru=sensitiveRuleHandle({p:{info:{url:v.ru}}},GS.secondSett).p.info.url;
          h5RelatedEventsSecond.push({k,ent,sin,v});
  }
  /**
   * @description 资源数据处理
   * @param {*} data 回调资源数据
   **/
  function WebviewResourceInfoHandle(data){
      let dataArr = data.p || [];
      forEach(dataArr, function (item) {
          const baseData = new Metric(item, GC.RESOURCE);
          baseData.info(GC.START_TIME, 0, 'st')
              .info(GC.NAME, '', 'name')
              .info(GC.DURATION, 0, 'dura')
              .info('ret','','rt')
              .metric(GC.FETCH_START, 0, 'fs')
              .metric(GC.DOMAIN_LOOKUP_START, 0, 'dls')
              .metric(GC.DOMAIN_LOOKUP_END, 0, 'dle')
              .metric(GC.CONNECT_START, 0, 'cs')
              .metric(GC.CONNECT_END, 0, 'ce')
              .metric(GC.SECURE_CONNECTION_START, 0, 'scs')
              .metric(GC.REQUEST_START, 0, 'reqs')
              .metric(GC.RESPONSE_START, 0, 'rsps')
              .metric(GC.RESPONSE_END, 0, 'rspe')
              .metric(GC.TRANSFER_SIZE, 0, 'ts')
              .metric(GC.ENCODED_BODY_SIZE, 0, 'ebs')
              .metric(GC.DECODED_BODY_SIZE, 0, 'dbs')
              .metric(GC.RESPONSE_STATUS,-1,'rs');
              if(isDefined(item.info)&&isDefined(item.info[GC.INITIATOR_TYPE])){
                  baseData.info(GC.INITIATOR_TYPE,'','it');
              }
              let unit=baseData.build().data;
              if(isDefined(unit.it)&&!data.special){
                  if((unit.it!=='xmlhttprequest'&&unit.it!=='fetch')){
                      h5Event.wri.push(unit);
                      /*转化的网络*/
                      const {type:k,ent:ent,sin:sin,data:v}=WebviewPerformanceToNet(WebviewPerformanceResourceTransformNet(unit));
                      h5RelatedEvents.push(JSON.parse(JSON.stringify({k,ent,sin,v})));
                      v.ru=sensitiveRuleHandle({p:{info:{url:v.ru}}},GS.secondSett).p.info.url;
                      h5RelatedEventsSecond.push({k,ent,sin,v});
                  }
              }else {
                  h5Event.wri.push(unit);
              } 
  });    
  }
  /**
   * @description revts数据处理
   * @param {*} data 回调revts数据
   **/
  function revtsHandle(data){
      if(isEmpty(h5Event.wpi)){
          return null
      }
      let webviewEvent=new Metric({info:h5Event},GC.WEBVIEWDATA);
      webviewEvent.info("pvid","",'pvid')
      .info("url","","url")
      .info("wpi",{},"wpi")
      .info("ic",false,"ic");
      if(h5Event.wri.length>0){
          webviewEvent.info("wri",[],"wri");
      }
      if(isDefined(data.revts)&&data.revts.length>0){
          let baseData=webviewEvent.build();
          baseData.revts=data.revts;
          return baseData
      }
      return webviewEvent.build()
  }
  /**
   *@descripe 获取IP与端口 此处有问题，不予采纳，原胡琪写的
   **/
  // function getIP(url) {
  //     let baseUrl=url.split("?")[0]
  //     if (baseUrl) {
  //       var rez = /(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\:([0-9]{1,5})/
  //       if (rez.test(baseUrl)) {
  //         return [`${RegExp.$1}.${RegExp.$2}.${RegExp.$3}.${RegExp.$4}`,Number(RegExp.$5)]
  //       } else if (/\:([0-9]{1,5})/.test(baseUrl)) {
  //         return ['', Number(RegExp.$1)]
  //       } else if (baseUrl.indexOf('https') > -1) {
  //         return ['', 443]
  //       } else {
  //         return ['',80]
  //       }
  //     }
  //     return ['',443]
  // }
  /**
   * @descripe 主文档转化network
   **/
  function WebviewPerformanceTimingTransformNet(data,url,pvid){
      if(url==="about:blank"){
          return
      }
      let timing=data;
      let IpAndPort=getIP(url);
      let ret = getMineTypeByUrl(url)|| 'text/html';
      let _dt=(timing.dle-timing.dls)*1000;
      if(_dt<0){
          _dt=0;
      }
      let _sslt=(timing.ce-timing.scs)*1000||-1;
      if(_sslt<0 ||timing.scs===0){
          _sslt=0;
      }
      let _rt=(timing.reqs-timing.ce)*1000||-1;
      if(_rt<-1){
          _rt=999;
      }else if(_rt===-1){
          _rt=0;
      }
      let _rti=(timing.rsps-timing.reqs)*1000||-1;
      if(_rti<-1){
          _rti=999;
      }else if(_rti===-1){
          _rti=0; 
      }
      let _dti=0;
      if(timing.rsps===0){
          _dti=(timing.rspe-timing.fs)*1000||-1;
      }else {
          _dti=(timing.rspe-timing.rsps)*1000||-1;
      }
      if(_dti<-1){
          _dti=999;
      }else if(_dti===-1){
          _dti=0;
      }

      let NetStruct={
          info:{
              id:uuid(),
              ru:url,
              m:"GET",
              ti:IpAndPort[0] || "",
              tp:IpAndPort[1] || "",
              dt:_dt,
              sslt:_sslt,
              rt:_rt,
              rti:_rti,
              dti:_dti,
              ds:0,
              rds:0,
              pt:url.indexOf('https')>-1 ? 2 : 1,
              ec:200,
              art:1,
              ret:ret,
              pvid:pvid,
              ic:false
          }
      };
      NetStruct.info.ct=timing.ce-timing.cs>0?(timing.ce-timing.cs)*1000:0;
      if(NetStruct.info.ti.length<1){
          delete NetStruct.info.ti;
      }
      return NetStruct
  }
  /**
   * @descripe 资源转化为network
   **/
  function WebviewPerformanceResourceTransformNet(data){
      let timing=data;
      let url=timing.name.slice(0,4096);
      let art=3;
      if(isDefined(timing.it)){
          switch (timing.it){
              case 'xmlhttprequest':
                  art=3;
                  break
              case 'beacon':
                  art=5;
                  break
              case 'fetch':
                  art=4;
                  break
              default:
                  art=2;

          }
      }
      let IpAndPort=getIP(url);
      let ret = getMineTypeByUrl(url)|| 'text/html';
      let _dt=(timing.dle-timing.dls)*1000;
      if(_dt<0 ||timing.dura<=10){
          _dt=0;
      }
      let _sslt=(timing.ce-timing.scs)*1000||-1;
      if(_sslt<0 || timing.dura<=10 || timing.scs===0){
          _sslt=0;
      }
      let _rt=(timing.reqs-timing.ce)*1000||-1;
      if(_rt<-1 || timing.dura<=10 ){
          _rt=999;
      }else if(_rt===-1){
          _rt=0; 
      }
      let _rti=(timing.rsps-timing.reqs)*1000||-1;
      if(_rti<-1 || timing.dura<=10 ){
          _rti=999;
      }else if(_rti===-1){
          _rti=0;
      }
      let _dti=0;
      if(timing.rsps===0){
          _dti=(timing.rspe-timing.fs)*1000||-1;
      }else {
          _dti=(timing.rspe-timing.rsps)*1000||-1;
      }
      if(_dti<-1 || timing.dura<=10 ){
          _dti=999;
      }else if(_dti===-1){
          _dti=0;
      }
      let NetStruct={
          info:{
          timestamp:isDefined(timing.st)&&isDefined(window.performance)&&isDefined(window.performance.timing)?(window.performance.timing.navigationStart+timing.st)*1000:now(),
          id:uuid(),
          ru:url,
          m:"GET",
          ti:IpAndPort[0] || "",
          tp:IpAndPort[1] || "",
          dt:_dt,
          sslt:_sslt,
          rt:_rt,
          rti:_rti,
          dti:_dti,
          ds:0,
          rds:0,
          pt:url.indexOf('https')>-1 ? 2 : 1,
          ec:200,
          art:art,
          ret:ret,
          ic:false,
          pvid:isDefined(GS.sett.pageViewId)?GS.sett.pageViewId:''
          },
      };
      //处理计算ct
      let _ct=(timing.ce-timing.cs)*1000;
      NetStruct.info.ct=_ct>0 ? _ct : 0;
      //放到eventloop,防止阻塞用户页面加载,保证数据在h5后
      // 下面这行的作用是啥，不知道，先注释掉
      // setTimeout(()=>$emit({ t: GC.REQUEST_DATA, p: NetStruct,type:'transform'}),0)
      return NetStruct
  }

  function spanService(data){
      const baseData = new Metric(data.p, GC.SPAN);
      baseData.info('st')
      .info('n', '', 'n',true)
      .info('t','','t')
      .info('du',0,'du')
      .info('sta',0,'sta')
      .info('ic',false,'ic');
      if(isDefined(data.p.info)&&isDefined(data.p.info.da)){
          baseData.info('da',[],'da');
      }
      if(isDefined(data.p.info)&&isDefined(data.p.info.m)){
          baseData.info('m',[],'m');
      }
      if(isDefined(data.p.info)&&isDefined(data.p.info.tag)){
          baseData.info('tag',[],'tag');
      }
      if(isDefined(data.p.info)&&isDefined(data.p.info.stac)){
          baseData.info('stac','','stac');
      }
      if(isDefined(data.p.info)&&isDefined(data.p.info.sub)){
          baseData.info('sub',{},'sub');
      }
      return baseData.build();
  }

  /**
   * 绑定事件监听函数
   * @param {*} events:事件类型数组 
   */
  function buildEventListener(events) {
      //采集页面性能数据指标事件注册
      notifierOn(events, function (evt) {
          if (!isDefined(evt.p)) {
              return log('C144')
          }
          const type = evt.t;
          if (isDefined(evt.p) && isDefined(evt.p.info)&&!isDefined(evt.p.info[GC.PAGE_ID])) {
              evt.p.info[GC.PAGE_ID] = GS.sett.pageViewId;
              evt.p.info[GC.PAGE_URL] = sensitiveRuleHandle({p:{info:{url:isDefined(window.location)?window.location.href:""}}},GS.sett).p.info.url;        }
          let baseData = {};
          switch (type) {
              case GC.ERROR_DATA:
                  baseData=errorService(evt);
                  dataDevide(baseData,jsInternalBridge.webviewJSErrorEvent);
                  break;
              case GC.CONSOLE_DATA:
                  baseData=consoleService(evt);
                  dataDevide(baseData,jsInternalBridge.consoleEvent);
                  break;
              case GC.REQUEST_DATA:
                  /*只对非关联网络走network序列化*/
                  if(!(isDefined(evt)&&isDefined(evt.p)&&isDefined(evt.p.info.ai) || isDefined(evt.isRelatedH5)&&evt.isRelatedH5)){
                      /*处理副配置,有则处理,没有则不处理*/
                      if(!isEmpty(GS.secondSett)){
                          baseData=requestService(JSON.parse(stringify(evt)),GS.secondSett);
                          //推送数据进入发送队列
                          if (!isEmpty(baseData)) {
                              if(isDefined(GS.secondSett.osType)&&GS.secondSett.osType!==GC.BROWSER){
                                      jsInternalBridge.NetworkEvent(stringify({ent:baseData.ent,v:baseData.data}),GS.secondSett);
                              }else {
                                  pushQueueData(baseData);
                              }
                          }
                      }
                      /*处理主配置*/
                          baseData=requestService(JSON.parse(stringify(evt)),GS.sett);
                      /*处理主配置*/
                      if (!isEmpty(baseData)) {
                          if(isDefined(GS.sett.osType)&&GS.sett.osType!==GC.BROWSER){    
                              jsInternalBridge.NetworkEvent(stringify({ent:baseData.ent,v:baseData.data}),GS.sett);
                          }else {
                              pushQueueData(baseData); 
                          }
                      }
                  }
                  /*关联的操作网络回调原始数据*/
                  if(isDefined(evt)&&isDefined(evt.p.info)&&isDefined(evt.p.info.ai)){
                          notifierEmit({t:GC.LIFESTYLE_REQUEST_END+evt.p.info.ai,requestData:JSON.parse(stringify(evt)),endTime:now()});
                  }
                  /*发布给H5订阅*/
                  if(isDefined(evt.isRelatedH5)&&evt.isRelatedH5){
                      notifierEmit({t:GC.LIFESTYLE_REQUEST_END+"H5",requestData:JSON.parse(stringify(evt)),endTime:now()});
                  }
                  /*发布给订阅者(路由),普通订阅*/
                      notifierEmit({t:GC.LIFESTYLE_REQUEST_END,requestData:JSON.parse(stringify(evt)),endTime:now()});
                  break;
              case GC.SPAN_DATA:
                  baseData=spanService(evt);
                  if(isDefined(baseData.data)){
                      notifierEmit({t:GC.SPAN_CALLBACK_DATA,websocketData:baseData});
                  }
                  /*非关联的span才上报*/
                  if(!baseData.isRelated){
                      dataDevide(baseData,jsInternalBridge.spanEvent);
                  }
                  break;
              case GC.RESOURCE_DATA:
                  if(evt.type===1){
                      WebviewPerformanceInfoHandle(evt);
                  }
                  if(evt.type===2){
                      WebviewResourceInfoHandle(evt);
                  }
                  /*前置配置数据*/
                  if(evt.type===3){
                      baseData=revtsHandle(evt);
                      if(isDefined(baseData)){
                          if(isDefined(GS.sett.osType)&&GS.sett.osType!==GC.BROWSER){  
                              let imd =window.top&&window.self&&window.top===window.self?1:0;
                              // baseData.data.wpi.imd=imd
                              baseData.imd=imd;
                              let result={
                                  ent:baseData.ent,
                                  v:baseData.data,
                                  // imd:imd
                              };
                              if(isDefined(baseData.revts)&&baseData.revts.length>0){
                                  baseData.revts.map(function(item){
                                      if(item.v.ru.split("?")[0]==window.location.href.split("?")[0]){
                                          item.v.imd=imd;
                                      }
                                      return item
                                  });
                                  result.revts=baseData.revts;
                              }
                              /*移动端2.1增加network采集控制*/
                              if(!checkMoudle('network')){
                                  delete result.revts;
                              }
                              jsInternalBridge.webviewPerformanceTimingEvent(stringify(result),GS.sett,imd);
                          }else {
                              pushQueueData(baseData); 
                          }
                      }
                  }
                  /*后置配置数据*/
                  if(evt.type===4){
                      baseData=revtsHandle(evt);
                      if(isDefined(baseData)){
                          if(isDefined(GS.secondSett.osType)&&GS.secondSett.osType!==GC.BROWSER){   
                              let imd =window.top&&window.self&&window.top===window.self?1:0;
                              // baseData.data.wpi.imd=imd
                              baseData.imd=imd;
                              /*url脱敏*/
                              baseData.data.url=sensitiveRuleHandle({p:{info:{url:baseData.data.url}}},GS.secondSett).p.info.url;                            let result={
                                  ent:baseData.ent,
                                  v:baseData.data,
                                  // imd:imd
                              };
                              if(isDefined(baseData.revts)&&baseData.revts.length>0){
                                  baseData.revts.map(function(item){
                                      if(item.v.ru.split("?")[0]==window.location.href.split("?")[0]){
                                          item.v.imd=imd;
                                      }
                                      return item
                                  });
                                  result.revts=baseData.revts;
                              }
                              /*移动端2.1增加network采集控制*/
                              if(!checkMoudle('network')){
                                  delete result.revts;
                              }
                              jsInternalBridge.webviewPerformanceTimingEvent(stringify(result),GS.secondSett,imd);
                          }else {
                              pushQueueData(baseData); 
                          }
                      }
                  }
                  break;
              case GC.TRACE_ACTION_DATA:
                  baseData=actionService(evt);
                  /*前置配置传递*/
                  if(isDefined(evt.type)&&evt.type===1){
                      if(isDefined(GS.sett.osType)&&GS.sett.osType!==GC.BROWSER){
                          let result={ent:baseData.ent,v:baseData.data};
                          if(isDefined(baseData.revts)&&baseData.revts.length>0){
                              result.revts=baseData.revts;
                          }
                          jsInternalBridge.webviewActionEvent(stringify(result),GS.sett);
                      }else {
                          pushQueueData(baseData);
                      }
                  }
                  /*后置配置*/
                  if(isDefined(evt.type)&&evt.type===2){
                      if(isDefined(GS.secondSett.osType)&&GS.secondSett.osType!==GC.BROWSER){
                          /*vn脱敏*/
                          baseData.data.vn=sensitiveRuleHandle({p:{info:{url:baseData.data.vn}}},GS.secondSett).p.info.url;
                          let result={ent:baseData.ent,v:baseData.data};
                          if(isDefined(baseData.revts)&&baseData.revts.length>0){
                              result.revts=baseData.revts;
                          }
                          jsInternalBridge.webviewActionEvent(stringify(result),GS.secondSett);
                      }else {
                          pushQueueData(baseData);
                      }
                  }
                  break
              default:
                  log('C118');
                  break
          }
      });
  }
  /*
  *初始化数据处理服务
  */
  function service(){
      let eventType=[GC.ROUTE_DATA,GC.ERROR_DATA,GC.CONSOLE_DATA,GC.REQUEST_DATA,GC.TRACE_ACTION_DATA,GC.SPAN_DATA,GC.RESOURCE_DATA,GC.PAGE_DATA];
      buildEventListener(eventType);
  }

  // 实现document.ready方法，原本document不带这个方法
  function docReady() {
      var ie = !!(window.attachEvent && !window.opera);
      var wk = /webkit\/(\d+)/i.test(navigator.userAgent) && (RegExp.$1 < 525);
      var fn = [];
      var run = function () {
          for (var i = 0; i < fn.length; i++) {
              fn[i]();
          }
      };
      var d = document;
      d.ready = function (f) {
          if (! ie && ! wk && d.addEventListener) {
              return d.addEventListener('DOMContentLoaded', f, false);
          }
          if (fn.push(f) > 1) {
              return;
          }
          if (ie) {
              (function () {
                  try {
                      d.documentElement.doScroll('left');
                      run();
                  } catch (err) {
                      setTimeout(arguments.callee, 0);
                  }
              })();
          } else if (wk) {
              var t = setInterval(function () {
                  if (/^(loaded|complete)$/.test(d.readyState)) {
                      clearInterval(t),
                      run();
                  }
              }, 0);
          }
      };
  }

  // 通过url控制探针不启动，主要用来再客户问题排查上
  function checkStatus() {
      if (/BonreeRUM=0/.test(window.location.search)) {
          GS.checkProbability(0);
          return false
      }
      return true
  }

  // 监控页面状态变化，后续业务逻辑处理用到这些数据
  function listenDoc(){
      notifierOn([GC.PAGE_READY,GC.PAGE_LOAD],(evt)=>{
          if (evt.t === GC.PAGE_READY) {
              globalData.changeState(1);
          } else {
              globalData.changeState(2);
          }
      });
  }

  function autoRun() {
      if(!checkStatus()){
          log("C106",true);
          return false
      }
      // 初始化document.ready方法后，再进行
      docReady();
      listenDoc();
      if(document.ready(function(){
          if(document.title){
              globalData.setData(GC.TITLE,document.title);
          }
      }))
      if (isDefined(window)) { // 挂载桥接方法
          window.setJsBridge = function (winBridge) {
              window.bonreePrivateInterface = winBridge;
          };
      }
      try {
          let target = document.querySelector('#BonreeAgent');
          if (!isDefined(target)) {
              return false
          }
          let configData = target.getAttribute('data');
          configData = window.decodeURIComponent && window.decodeURIComponent(configData);
          if (isJSON(configData)) {
              configData = JSON.parse(configData);
              if (!isDefined(configData['appId'])) {
                  log('C101', true);
              }
              // 判断是不是拨测端，增加标识，后续处理数据上报流程
              if(isDefined(window.getIsRunWithNetClient)){
                  configData['dataFusionInfo']="net";
              }
              if(isDefined(window.bonreeRUM)){
                  /*页面已经注入js*/
                  window.bonreeRUM.config(configData,false,1);
              }else {
                  /*页面没有注入js*/
                  GS.setConfig(configData);
              }
              GS.sett.initTime=now();
              if (GS.sett.probability) {
                  return true
              } else {
                  log("C103", true);
              }
          } else {
              log("C102", true);
              return false
          }
      } catch (error) {
          log("C102", true);
          return false
      }
      return true
  }

  // 自执行模块有确定探针启动不启动的逻辑
  let autoCheck = autoRun();
  if (autoCheck) {
      init();
  }
  function init() {
      if (!window.bonreeRUM) {
          window.BonreeRecord={"BonreeRecord":BonreeRecord};
          dataEngine();  // 启动探针采集数据
          service();     // 启动数据处理服务
          pusher();      // 启动数据上报服务
      } else {
          //探针采集层已经启动，不做二次启动
          log("C104");
          return
      }
  }

  function BonreeStart(config) {
      // 判断是不是拨测端
      if(isDefined(window.getIsRunWithNetClient)){
          config['dataFusionInfo']="net";
      }
      if(!isDefined(window.bonreeRUM)){
          GS.setConfig(config);
      }else {
          /*此处是移动端注入的变量隔离不能直接调用到已注入的实例,故需要这样设置保证设置后置配置到统一实例下*/
          if(isDefined(window.bonreeRUM.config)){
               window.bonreeRUM.config(config,false,1);
               return
           }
      }
      /*cmt*/
      GS.sett.initTime=now();
      init();
  }

  const BonreeAgent={
      BonreeRecord, BonreeStart, Sm4,
      getDeviceInfo, setExtraInfo,
      setUserID
  };
  window.BonreeAgent=BonreeAgent;

  exports.BonreeRecord = BonreeRecord;
  exports.BonreeStart = BonreeStart;
  exports.Sm4 = Sm4;
  exports.getDeviceInfo = getDeviceInfo;
  exports.setExtraInfo = setExtraInfo;
  exports.setUserID = setUserID;

}));
